language = {'what is your name:':'I am Tom','how old are you?':'25','bye':'bye!'} HOST = "127.0.0.1" PORT = 6666 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((HOST,PORT)) s.listen(1) print("Listing at port 6666") conn,addr = s.accept() print("connect by:",addr) while True: data = conn.recv(1024) data = data.decode() if not data: break print('received message:',data) conn.sendall(language.get(data,'Nothing').encode()) conn.close() s.close()
2. 客户端代码(client.py):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import socket,sys host = "127.0.0.1" port = 6666 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host,port)) except Exception as e: sys.exit() while True: c = input("YOU SAY:") s.sendall(c.encode()) data = s.recv(1024) data = data.decode() print('Recived:', data) if c.lower() == '再见': break s.close()