UDP远程AI聊天机器人
2019-07-07 本文已影响0人
Vector_Wan
未使用任何人工智能接口,,,所以聊起来有点智障,,,
主要是练习一下 python 的网络编程和正则表达式。
先放运行效果:
客户端:
服务器端:
话不多说先上源码:
首先是服务器端:
# @Time : 2019/7/7 10:08
# @Author : Vector_Wan
# @Email : 995626309@qq.com
# File : UDP_Server.py
# Software: PyCharm
from socket import *
from time import ctime
import re
HOST = ''
PORT = 9000
BUFSIZ = 1024
ADDR = (HOST, PORT)
udpSerSock = socket(AF_INET, SOCK_DGRAM)
while True:
# 接收数据
print('waiting for message...')
data, addr = udpSerSock.recvfrom(BUFSIZ)
# 处理数据
m = re.match(r'你(\D{1,})吗\?', data.decode('utf-8'))
if m == None:
data = '对不起,我没听清,请再说一次。'
else:
data = '我' + m.groups(1)[0] + '!'
content = '[ {} ] {}'.format(bytes(ctime(), "utf-8"), data)
# 返回数据
udpSerSock.sendto(content.encode('utf-8'), addr)
print('...received from and returned to:', addr)
print('...recived from and return to:', addr)
客户端:
# @Time : 2019/7/7 10:50
# @Author : Vector_Wan
# @Email : 995626309@qq.com
# File : UDP_Client.py
# Software: PyCharm
from socket import *
HOST = 'localhost'
PORT = 9000
BUFFSIZ = 1024
ADDR = (HOST, PORT)
udpCliSock = socket(AF_INET, SOCK_DGRAM)
while True:
data_send = input('>> ')
if not data_send:
break
udpCliSock.sendto(data_send.encode('utf-8'), ADDR)
data_recv, ADDR = udpCliSock.recvfrom(BUFFSIZ)
if not data_recv:
break
print(data_recv.decode('utf-8'))
udpCliSock.close()