Python 多路複用之selectors
阿新 • • 發佈:2018-12-15
- server端
# I/O多路複用 import selectors import socket def accept(sock, mask): conn, addr = sock.accept() # 得到連線物件conn conn.setblocking(False) # 設定為非阻塞 sel.register(conn, selectors.EVENT_READ, read) # 把conn物件和對應的read方法註冊到sel物件 print(conn) def read(conn, mask): try: msg = conn.recv(1024) if msg: conn.send(msg) else: sel.unregister(conn) # 如果收到的訊息為空,登出conn物件,對於linux系統 except ConnectionResetError as e: print(e) sel.unregister(conn) # 連線突然中斷,登出conn物件,對於windows系統 sel = selectors.DefaultSelector() # 建立selectors物件 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立socket物件 sock.bind(('127.0.0.1', 8090)) sock.listen(100) sock.setblocking(False) # 設定socket物件為非阻塞 sel.register(sock, selectors.EVENT_READ, accept) # 把sock物件和對應的accept方法註冊到sel物件 while True: events = sel.select() # 監聽已經註冊的物件 for key, mask in events: callback = key.data # 回還函式 callback(key.fileobj, mask) # 呼叫回還函式
- client端
import socket
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.connect(('127.0.0.1', 8090))
while True:
msg = input('>>>').strip()
if msg:
conn.send(msg.encode('utf-8'))
msg = conn.recv(1024)
print(msg.decode('utf-8'))