TCP template 代码
服务端
1 from socket import * 2 3 server= socket(AF_INET,SOCK_STREAM) 4 server.bind(('127.0.0.1',8080)) 5 server.listen(5) 6 7 while True: 8 client,client_addr=server.accept() 9 while True: 10 try: 11 data=client.recv(1024).decode('utf-8') 12 if not data:break 13 print(data) 14 client.send(data.encode('utf-8')) 15 except ConnectionResetError: 16 print('客户端异常关闭') 17 break 18 client.close() 19 20 server.close()
客户端
1 from socket import * 2 3 client= socket(AF_INET,SOCK_STREAM) 4 client.connect(('127.0.0.1',8080)) 5 6 while True: 7 msg=input('>>>').strip() 8 if not msg:continue 9 client.send(msg.encode('utf-8')) 10 data=client.recv(1024).decode('utf-8') 11 print(data) 12 13 client.close()