Python套接字通信(多线程自动回复机器人)
程序员文章站
2023-11-21 13:03:34
Receiverimport socketfrom os.path import commonprefixwords = {'hello':'Hello', 'Who are you?':'Servicer', 'over':'Over'}HOST = ''PORT = 5000s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((HOST, PORT)) #绑定地址s....
Receiver:
import socket
from os.path import commonprefix
from threading import Thread
def reply(conn,addr):
global words
while True:
data = conn.recv(1024).decode()
if not data:
break
print('Received message:', data,"connected by",addr)
m = 0
answer = ''
for k in words.keys():
data = ' '.join(data.split()) #以空格分割字符
if len(commonprefix([k, data])) > len(k)*0.6: #发送信息是否与存在问题前缀有60%重合
answer = k
break
#若发送信息是乱序,则以集合分割发送信息和存在问题,选择有最多共有部分的问题来回复
length = len(set(data.split())&set(k.split()))
if length > m:
m = length
answer = k
conn.sendall(words.get(answer, "Sorry,I don't know what are you talking about.").encode())
conn.close()
words = {'hello':'Hello',
'Who are you?':'Servicer',
'over':'Over'}
HOST = ''
PORT = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT)) #绑定地址
s.listen(1) #开始监听
print('Listening on port:',PORT)
while True:
conn, addr = s.accept()
Thread(target=reply,args=(conn,addr,)).start()
s.close()
Sender:
import socket
import sys
# 服务端主机IP地址和端口号
HOST = '127.0.0.1'
PORT = 5000
#创建一个socket对象,
#socket.AF_INET表示IPV4,socket.AF_INET6表示IPV6
#socket.SOCK_STREAM表示TCP协议,socket.SOCK_DGRAM表示UDP协议
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()
mess=""
while mess.lower()!="over":
mess = input('Please input the content to send:')
s.sendall(mess.encode())
data = s.recv(1024).decode()
print('Received message:', data)
s.close()
本文地址:https://blog.csdn.net/weixin_43873198/article/details/107441331