服务端
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()
原文地址:https://www.cnblogs.com/Gluneko/p/9550961.html
时间: 2024-10-14 05:13:23