From 1e7160abbfaec11e359f7963b39e38696a40ea12 Mon Sep 17 00:00:00 2001 From: yumoqing Date: Sat, 26 Sep 2020 21:54:43 +0800 Subject: [PATCH] bugfix --- appPublic/background.py | 11 +++++++ appPublic/find_player.py | 64 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 appPublic/background.py create mode 100644 appPublic/find_player.py diff --git a/appPublic/background.py b/appPublic/background.py new file mode 100644 index 0000000..04d4c08 --- /dev/null +++ b/appPublic/background.py @@ -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) diff --git a/appPublic/find_player.py b/appPublic/find_player.py new file mode 100644 index 0000000..246b29c --- /dev/null +++ b/appPublic/find_player.py @@ -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 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 +