注意:需要先启动服务器,在启动客户端
TCP server
import socket from os.path import commonprefix words = { 'how are you?':"Fine thank you", 'how old are you?':'38', 'what is your name?':'Ji Ruan', "what's your name?":"Ji Ruan", 'where do you work?':'Nan Yang', 'bey':'Bye' } HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #绑定socket s.bind((HOST,PORT)) #开始监听一个客户端连接 s.listen(1) print("Linsten on port :" ,PORT) #阻塞等待客户端连接 conn,addr = s.accept() print("Connected by",addr) #开始聊天 while True: data = conn.recv(512).decode()#解码 if not data: break print("Received message:",data) # 尽量猜测对方要表达的真正意思 m = 0 key = '' for k in words.keys(): #删除多余的空白字符 data = ' '.join(data.split()) # 与某个 键接近,就直接返回 if len(commonprefix([k,data])) > len(k)* 0.7: key = k break # 使用选择发,选择一个重合度交的键 length = len(set(data.split()) & set(k.split())) if length > m: m = length key = k #选择适合信息进行回复 conn.sendall(words.get(key, 'Sorrey.').encode()) conn.close() s.close()TCP cilent
import socket import sys #服务端主机IP地址,和端口号 HOST = '127.0.0.1' PORT = 50007 s =socket.socket(socket.AF_INET,socket.SOCK_STREAM) try:#异常处理,当服务器未开启或者IP错误提示 #连接服务器 s.connect((HOST, PORT)) except Exception as e: print("Server not found or not open") print(e) sys.exit() while True: c = input("Input the content you want to send:") #发送数据 s.sendall(c.encode()) #从服务器接收数据 data = s.recv(512) data = data.decode() print("Received:" ,data) if c.lower() == 'bey': break #关闭连接 s.close()运行效果: