This commit is contained in:
yumoqing 2020-10-18 16:53:00 +08:00
commit 5185cededf
2 changed files with 75 additions and 0 deletions

11
appPublic/background.py Normal file
View File

@ -0,0 +1,11 @@
from threading import Thread
class Background(Thread):
def __init__(self,func, *args,**kw):
Thread.__init__(self)
self.__callee = func
self.__args = args
self.__kw = kw
def run(self):
self.__callee(*self.__args, **self.__kw)

64
appPublic/find_player.py Normal file
View File

@ -0,0 +1,64 @@
# !/usr/bin/env python
# -*- coding:UTF-8 -*-
from socket import *
import json
from appPublic.sockPackage import get_free_local_addr
from appPublic.background import Background
BUFSIZE = 1024
class BroadcastServer:
def __init__(self, port, info):
self.info = info
self.port = port
self.udpSerSock = socket(AF_INET, SOCK_DGRAM)
# 设置阻塞
self.udpSerSock.setblocking(1)
# 设置超时时间 0.5s
# self.udpSerSock.settimeout(0.5)
self.udpSerSock.bind(('' ,port))
self.run_flg = True
self.thread = Background(self.run)
self.thread.start()
def run(self):
while self.run_flg:
try:
print('broadcast_server():wait for receive...',self.port)
data, addr = self.udpSerSock.recvfrom(BUFSIZE)
print('broadcast_server(), received=',data,addr)
ret = json.dumps(self.info).encode('utf-8')
self.udpSerSock.sendto(ret, addr)
except Exception as e:
print('exception happened:',e)
pass
def stop(self):
self.run_flg = False
self.udpSerSock.close()
def find_players(port):
# broadcast_addr = '.'.join(host.split('.')[:-1]) + '.255'
host = get_free_local_addr()[0]
udpCliSock = socket(AF_INET, SOCK_DGRAM)
#设置阻塞
udpCliSock.setblocking(2)
#设置超时时间
udpCliSock.settimeout(2)
udpCliSock.bind(('', 0))
udpCliSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
print('find_players() port=',port)
udpCliSock.sendto(b'findplayers', ('255.255.255.255',port))
players = []
while True:
try:
data,addr = udpCliSock.recvfrom(BUFSIZE)
if addr[0] != host and data:
data = data.decode('utf-8')
d = json.loads(data)
d['ip'] = addr[0]
players.append(d)
except Exception as e:
print('error happened',e)
break
udpCliSock.close()
return players