阻塞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(b'hello 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'))