服务端:
import socket sock = socket.socket() sock.bind(("127.0.0.1",8899)) sock.listen(5) while True: print("server is waiting...") client_sock, client_addr = sock.accept() print(client_addr, client_sock) while True: data = client_sock.recv(1024) print('收到消息:' + data.decode()) if data == b'q': break res = input('输入>>>').encode() client_sock.send(res)
客户端:
import socket sock = socket.socket() sock.connect(("127.0.0.1",8899)) while True: data = input('输入>>>').encode() sock.send(data) if data == b'q': break res = sock.recv(1024).decode() print('收到消息:' + res) sock.close()
效果: