非阻塞套接字實現並發處理
阿新 • • 發佈:2018-08-28
pre ror enc con put 服務 生成 import data
服務端
import socket server = socket.socket() server.setblocking(False) server.bind((‘0.0.0.0‘,8080)) server.listen(1000) all_connection = []#所有連接的客戶端,用集合比列表更快 while True: try: connection,remote_address = server.accept()#非阻塞對等連接套接字生成 connection.setblocking(False)#connection是新生成的,也需要設置成非阻塞all_connection.append(connection) except BlockingIOError: pass to_handler = [connection for connection in all_connection] for connection in to_handler: try: recv_data = connection.recv(1024) if recv_data: print(recv_data) connection.send(recv_data)else: connection.close() all_connection.remove(connection)#如果這個客戶已經處理完畢,就移除 except BlockingIOError: pass
客戶端
import socket host = ‘192.168.215.128‘ port = 8080 client = socket.socket() client.connect((host,port)) # client.send(b‘haha‘) msg = input(‘-->‘) client.send(msg.encode(‘utf-8‘)) recv_data = client.recv(1024) print(recv_data.decode(‘utf-8‘)) client.close()
非阻塞套接字實現並發處理