server 端代码
import time,threading,logging,datetime,socket
# FOMAT=" %(asctime)s %(threadName)s %(thread)d %(message)s"
# logging.basicConfig(format=FOMAT,level=logging.INFO)
FORMAT= "%(asctime)s %(threadName)s %(thread)d %(message)s "
logging.basicConfig(format=FORMAT,level=logging.INFO)
class serverUDP():
def __init__(self,ip='127.0.0.1',pory=9090,times=10):
self.sock=socket.socket(type=socket.SOCK_DGRAM)
self.addr=ip,pory
self.event=threading.Event()
self.clients={}
self.times=times
def start(self):
self.sock.bind(self.addr) #启动并占用udp端口
threading.Thread(target=self.recv,name='recv').start()
def recv(self):
while not self.event.is_set():
data,clieninfo=self.sock.recvfrom(1024)
cureent = datetime.datetime.now().timestamp()
logging.info(data)
if data.strip()== b'^hb--': #心跳机制
self.clients[clieninfo] = cureent
logging.info("{}b>>>>>>>>>>>>".format(clieninfo))
continue
if data.strip()==b'quit':
self.clients.pop(clieninfo)
logging.info("{} pas".format(clieninfo))
continue
self.clients[clieninfo]=cureent
msg="---{} from [{}:{}]-{}".format(datetime.datetime.now(),*clieninfo,data.decode()).encode()
rmkey=set()
for i,stamp in self.clients.items():
if cureent -stamp < 0 or cureent - stamp>self.times:
rmkey.add(i)
else:
self.sock.sendto(msg,i)
for i in rmkey:
self.clients.pop(i)
def stop(self):
self.event.is_set()
self.clients.clear()
self.sock.close()
UD=serverUDP()
UD.start()
while True:
cmd=input(">>").strip()
if cmd=='quit':
UD.stop()
break
logging.info(threading.enumerate())
client端代码
import time,threading,logging,datetime,socket
# FOMAT=" %(asctime)s %(threadName)s %(thread)d %(message)s"
# logging.basicConfig(format=FOMAT,level=logging.INFO)
FORMAT= "%(asctime)s %(threadName)s %(thread)d %(message)s "
logging.basicConfig(format=FORMAT,level=logging.INFO)
class clientUDP():
def __init__(self,rip='127.0.0.1',rport=9090,times=5):
self.sock=socket.socket(type=socket.SOCK_DGRAM)
self.raddr=rip,rport
self.even=threading.Event()
self.times=times
def start(self):
self.sock.connect(self.raddr)
self.send("{}hello".format(self.sock.getsockname()))
threading.Thread(target=self.heartbeat,name='heartbeat',daemon=True).start()
threading.Thread(target=self.recv,name='recv').start()
def heartbeat(self):
while not self.even.wait(self.times):
self.sock.send(b'^hb--')
def recv(self):
while not self.even.is_set():
data=self.sock.recvfrom(1024)
logging.info(data)
def send(self,msg:str):
self.sock.sendto(msg.encode(),self.raddr)
def stop(self):
self.even.set()
self.send('quit')
self.sock.close()
UP=clientUDP()
UP.start()
while True:
cmd=input(">>>>").strip()
if cmd=='quit':
socket.close( )
break
UP.send(cmd)
logging.info(threading.enumerate())