本文代码简单模拟了机器人聊天软件原理,服务端提前建立好字典,然后根据接收到的内容自动回复。当然,这个程序对客户端的信息是进行严格匹配,大家可以尝试结合分词模块和人工智能知识,设计一个合适的模糊匹配算法,就可以实现更好的聊天机器人了。
服务端代码:
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()
if not data:
break
print('Received message:', data)
conn.sendall(words.get(data, 'Nothing').encode())
conn.close()
s.close()
客户端代码:
import socket
#服务端主机IP地址和端口号
HOST = '127.0.0.1'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
#连接服务器
s.connect((HOST, PORT))
except Exception as e:
print('Server not found or not open')
sys.exit()
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()
运行效果如图: