服务端
import socketserver = 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 sockethost = '192.168.215.128'port = 8080client = 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()