# 服务端: import socket server = socket.socket() server.bind(('127.0.0.1',8081)) server.listen(5) while True: sock, addr = server.accept() while True: try: data = sock.recv(1024) if len(data) == 0: break print(f'来自客户端{addr}的消息>>>:',data.decode('utf8')) msg = input('请输入你要发送给客户端的消息(不能发送空消息)>>>:').strip() sock.send(msg.encode('utf8')) except BaseException: break # 客户端: import socket client = socket.socket() client.connect(('127.0.0.1',8081)) while True: msg = input('请输入你想要给服务端发送的消息>>>:').strip() if len(msg) == 0: print('不能发送空消息') continue client.send(msg.encode('utf8')) data = client.recv(1024) print('来自服务端发送的消息>>>:',data.decode('utf8'))
标签:socket,utf8,代码优化,msg,data,服务端,客户端 From: https://www.cnblogs.com/juzijunjun/p/16897563.html