apppublic/appPublic/udp_comm.py

81 lines
2.0 KiB
Python
Raw Normal View History

2021-06-17 15:44:10 +08:00
# -*- coding:UTF-8 -*-
2021-07-16 13:12:39 +08:00
from traceback import print_exc
2021-06-17 15:44:10 +08:00
from socket import *
import json
from appPublic.sockPackage import get_free_local_addr
from appPublic.background import Background
2021-07-13 16:13:59 +08:00
BUFSIZE = 1024 * 64
2021-06-17 15:44:10 +08:00
class UdpComm:
def __init__(self, port, callback, timeout=1):
self.callback = callback
2021-06-17 15:55:15 +08:00
self.timeout = timeout
2021-06-17 15:44:10 +08:00
self.host = get_free_local_addr()[0]
self.port = port
self.udpSerSock = socket(AF_INET, SOCK_DGRAM)
# 设置阻塞
self.udpSerSock.setblocking(1)
# 设置超时时间 1s
# self.udpSerSock.settimeout(timeout)
self.udpSerSock.bind(('' ,port))
self.run_flg = True
self.thread = Background(self.run)
self.thread.start()
def run(self):
while self.run_flg:
try:
b, addr = self.udpSerSock.recvfrom(BUFSIZE)
if addr[0] != self.host:
2021-07-14 14:33:00 +08:00
self.callback(b, addr)
2021-06-17 15:44:10 +08:00
except Exception as e:
print('exception happened:',e)
2021-07-16 13:12:39 +08:00
print_exc()
2021-06-17 15:44:10 +08:00
pass
def stop(self):
self.run_flg = False
self.udpSerSock.close()
def broadcast(self, data):
broadcast_host = '.'.join(self.host.split('.')[:-1]) + '.255'
udpCliSock = socket(AF_INET, SOCK_DGRAM)
udpCliSock.settimeout(self.timeout)
udpCliSock.bind(('', 0))
udpCliSock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
2021-07-13 16:13:59 +08:00
b = data
if not isinstance(data, bytes):
b = json.dumps(data).encode('utf-8')
2021-06-17 15:44:10 +08:00
udpCliSock.sendto(b, (broadcast_host,self.port))
2021-07-13 16:13:59 +08:00
2021-06-17 15:44:10 +08:00
def send(self,data,addr):
2021-07-13 16:13:59 +08:00
b = data
if not isinstance(data, bytes):
b = json.dumps(data).encode('utf-8')
2021-06-18 12:34:35 +08:00
if isinstance(addr,list):
2021-06-18 12:29:30 +08:00
addr = tuple(addr)
2021-06-17 15:44:10 +08:00
self.udpSerSock.sendto(b,addr)
def sends(self,data, addrs):
2021-07-13 16:13:59 +08:00
b = data
if not isinstance(data, bytes):
b = json.dumps(data).encode('utf-8')
2021-06-17 15:44:10 +08:00
for addr in addrs:
2021-06-18 12:34:35 +08:00
if isinstance(addr,list):
2021-06-18 12:29:30 +08:00
addr = tuple(addr)
2021-06-17 15:44:10 +08:00
self.udpSerSock.sendto(b,addr)
2021-06-17 15:49:17 +08:00
if __name__ == '__main__':
import sys
def msg_handle(data, addr):
print('addr:', addr, 'data=', data)
2021-06-18 11:30:11 +08:00
port = 50000
if len(sys.argv)>1:
port = int(sys.argv[1])
d = UdpComm(port, msg_handle)
2021-06-17 15:49:17 +08:00
x = input()
while x:
d.broadcast(x)
x = input()