socket 反复连接
import socket def start_server(): # 创建一个TCP/IP套接字 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定到地址和端口 server_address = ('localhost', 12345) print(f'Starting up on {server_address[0]} port {server_address[1]}') server_socket.bind(server_address) # 开始监听连接 server_socket.listen(1) while True: # 等待客户端连接 print('Waiting for a connection') connection, client_address = server_socket.accept() try: print(f'Connection from {client_address}') # 接收数据并发送回客户端 while True: data = connection.recv(1024) print(f'Received {len(data)} bytes from {client_address}') if data: print(f'Sending data back to the client') connection.sendall(data) else: print('No more data from', client_address) break finally: # 清理连接 connection.close() if __name__ == '__main__': start_server()