实现多个客户端能够使用UDP协议互相发送消息
创建一个UDP服务器接收连接的UDP客户端,并把要发送的消息转发到队友的客户端主机上
from socket import *
from time import ctime
import re
HOST=''
PORT=21567
BUFSIZE=1024
ADDR=(HOST,PORT)
udpS=socket(AF_INET,SOCK_DGRAM)
udpS.bind(ADDR)
talkPair={}
print("waiting...............")
while True:
data,addr=udpS.recvfrom(BUFSIZE)
srcData=data.decode()
talkName=re.match("^U:(\w+):$",srcData)
if talkName:
talkName=talkName.group(1)
print(talkName)#用户注册用户名
if talkName not in talkPair.keys():
talkPair[talkName]=addr#字典关联socket
sRes="welcome %s "%talkName
udpS.sendto(sRes.encode(),addr)
else:
sRes="The name exsit"
udpS.sendto(sRes.encode(),addr)
else:#判断是否是发给某个人的
talkName=re.match("^T:(\w+):",srcData)
print(talkName)
if talkName:
talkName=talkName.group(1)
if talkName:#判断发给某个人的姓名是否存在
if talkName in talkPair.keys():#查找socket通信
udpS.sendto(srcData.encode(),talkPair[talkName])
else:#发给某人的不存在提示用户不存在
sRes="No this one"
udpS.sendto(sRes.encode(),addr)
else:
sRes="Can't identify info"
udpS.sendto(sRes.encode(),addr)
udpS.close()
from socket import *
import threading,re
HOST='localhost'
PORT=21567
BUFSIZE=1024
ADDR=(HOST,PORT)
tC=socket(AF_INET,SOCK_DGRAM)
Tflag=True
def action(tC):
while True:
data,addr=tC.recvfrom(BUFSIZE)
sRes=data.decode()
talkName=re.match("^T:(\w):(.*)",sRes)#匹配通信的用户名
if talkName:
print(">",talkName.group(1)," say:",talkName.group(2))
else:
print(sRes)
t=threading.Thread(target=action,args=(tC,))
try:
while Tflag:
data=input(">")
if data == '88':
break
tC.sendto(data.encode(),ADDR)
if t.is_alive() is False:
t.start()
except KeyboardInterrupt as e:
print(e)
tC.close()