2020-09-26 21:54:43 +08:00
|
|
|
# !/usr/bin/env python
|
|
|
|
# -*- coding:UTF-8 -*-
|
|
|
|
from socket import *
|
|
|
|
import json
|
|
|
|
from appPublic.sockPackage import get_free_local_addr
|
2020-09-26 22:25:56 +08:00
|
|
|
from appPublic.background import Background
|
2020-09-26 21:54:43 +08:00
|
|
|
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)
|
2020-10-29 10:51:59 +08:00
|
|
|
# 设置超时时间 1s
|
|
|
|
# self.udpSerSock.settimeout(1)
|
2020-09-26 21:54:43 +08:00
|
|
|
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)
|
|
|
|
#设置阻塞
|
2020-10-29 10:51:59 +08:00
|
|
|
#udpCliSock.setblocking(2)
|
2020-09-26 21:54:43 +08:00
|
|
|
#设置超时时间
|
2020-10-29 10:51:59 +08:00
|
|
|
udpCliSock.settimeout(0.5)
|
2020-09-26 21:54:43 +08:00
|
|
|
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
|
|
|
|
|