python利用TCP实现会聊天的小机器人 博客分类: python pythonTCP
程序员文章站
2024-02-09 11:07:10
...
一 代码
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)
whileTrue:
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))#连接连接
whileTrue:
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()#关闭连接
二 运行结果