时间:2021-07-01 10:21:17 帮助过:30人阅读
本文实例讲述了Python基于TCP实现会聊天的小机器人功能。分享给大家供大家参考,具体如下:
一 代码
1、服务端程序
import socket words ={'how are you?':'Fine,thank you.', 'how old are you?':'38', 'what is your name?':'Dong FuGuo', "what's your name?":'Dong FuGuo', 'where do you work?':'SDIBT', 'bye':'Bye'} HOST ='' PORT =50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #绑定socket s.bind((HOST, PORT)) #开始监听 s.listen(1) print('Listening at port:',PORT) conn, addr = s.accept() print('Connected by', addr) while True: data = conn.recv(1024) data = data.decode() ifnot data: break print('Received message:', data) conn.sendall(words.get(data,'Nothing').encode()) conn.close()
2、客户端程序
import socket HOST ='127.0.0.1'#服务端主机IP地址 PORT =50007#服务端主机端口号 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT))#连接连接 while True: c = input('Input the content you want to send:') s.sendall(c.encode())#发送数据 data = s.recv(1024)#从客户端接收数据 data = data.decode() print('Received:', data) if c.lower()=='bye': break s.close()#关闭连接
二 运行结果
相关推荐:
Python基于numpy模块创建对称矩阵的方法
Python基于time模块求程序运行时间的方法
以上就是Python基于TCP实现会聊天的小机器人功能的详细内容,更多请关注Gxl网其它相关文章!