python

超轻量级php框架startmvc

Python基于TCP实现会聊天的小机器人功能示例

更新时间:2020-05-27 12:12:01 作者:startmvc
本文实例讲述了Python基于TCP实现会聊天的小机器人功能。分享给大家供大家参考,具体如下

本文实例讲述了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 TCP 聊天 机器人