Python随心记--阻塞IO server

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python随心记--阻塞IO server相关的知识,希望对你有一定的参考价值。

阻塞IO server
import socket

sk = socket.socket()

sk.bind((127.0.0.1,8080))


while 1:
    conn,addr = sk.accept()
    while 1:
        conn.send(hello client.encode(utf8))
        data = conn.recv(1024)
        print(data.decode(utf8))

#client
import socket

sk = socket.socket()

sk.bind((127.0.0.1,8080))

while 1:
    data = sk.recv(1024)
    print(data.decode(utf8))
    sk.send(bhello server)
非阻塞IO server
import time,socket

sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.bind((127.0.0.1,6667))
sk.listen(5)
sk.setblocking(False)
while True:
    try:
        print(waiting client connection........)
        connection,addr = sk.accept()
        print(+++,addr)
        client_message = connection.recv(1024)
        print(str(client_message,utf8))
        connection.close()
    except Exception as e:
        print(e)
#client
import time,socket
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

while True:
    sk.connect((127.0.0.1,6667))
    print(hello)
    sk.sendall(bytes(hello,utf8))
    time.sleep(2)
    break
IO多路复用select监听 sewrver
#优势:可以监听多个连接
import socket,select
sk = socket.socket()
sk.bind((127.0.0.1,9904))
sk.listen(5)
inp = [sk,] 
while True:
    r,w,e = select.select(inp,[],[],5)
    for i in r:
        conn,addr = i.accept()
        print(hello)
        inp.append(conn)
    print(>>>>>>)

#client
import socket
sk = socket.socket()
sk.bind((127.0.0.1,9904))

while 1:
    inp = input(>>>:).strip()
    sk.send(inp.encode(utf8))
    data = sk.recv(1024)
    print(data.decode(utf8))
select触发方式
#水平触发
#边缘触发

异步IO :全程无阻塞

selectors模块介绍
import selectors,socket
sel = selectors.DefaultSelector()
def accept(sock,mask):
    conn,addr = sock.accept()
    print(accept,conn,from,addr)
    conn.setblocking(False)
    sel.register(conn,selectors.EVENT_READ,read)

def read(conn,mask):
    data = conn.recv(1000)
    if data:
        print(echoing,repr(data),to,conn)
        conn.send(data)
    else:
        print(closing,conn)
        sel.unregister(conn)
        conn.close()

sock = socket.socket()
sock.bind((localhost,8090))
sock.listen(100)
sock.setblocking(False)   #设置非阻塞
sel.register(sock,selectors.EVENT_READ,accept)

while True:
    events = sel.select()
    for key,mask in events:
        callable = key.data
        callable(key.fileobj,mask)

#client
import socket
sk = socket.socket()
sk.connect((127.0.0.1,8090))

while 1:
    inp = input(>>>:).strip()
    sk.send(inp.encode(utf8))
    data = sk.recv(1024)
    print(data.decode(utf8))

 








以上是关于Python随心记--阻塞IO server的主要内容,如果未能解决你的问题,请参考以下文章

非阻塞IO

python并发学习总结

python IO非阻塞模型

python-- 事件驱动介绍阻塞IO, 非阻塞IO, 同步IO,异步IO介绍

Python学习:并发编程之IO模型

前端随心记---------Javascript系列(第八节.BOM)