jsb-netgame/network.py

68 lines
1.7 KiB
Python
Raw Normal View History

2024-02-17 17:05:21 +00:00
import socket, os, sys, json
2024-01-27 16:56:24 +00:00
from threading import Thread, Lock
2024-02-10 12:30:58 +00:00
NETTRACE = str(os.environ.get("NETTRACE", "0")) == "1"
2024-01-27 16:56:24 +00:00
class Sock:
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
2024-02-03 17:57:23 +00:00
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
2024-01-27 16:56:24 +00:00
self.queue = []
self.queue_lock = Lock()
self.sock_thread = None
2024-02-17 17:05:21 +00:00
def send_raw(self, message, address):
2024-02-03 15:58:24 +00:00
if type(message) == str:
message = message.encode()
2024-02-10 12:30:58 +00:00
if NETTRACE:
print("Send to", tuple(address), ":", message, file=sys.stderr)
self.sock.sendto(message, tuple(address))
2024-01-27 16:56:24 +00:00
2024-02-17 17:05:21 +00:00
def send(self, message, address):
message = json.dumps(message)
if NETTRACE:
print("Send to", tuple(address), ":", message, file=sys.stderr)
self.sock.sendto(message.encode(), tuple(address))
2024-01-27 16:56:24 +00:00
def listen(self, address, length=65535):
2024-02-10 12:30:58 +00:00
self.sock_thread = SockThread(self, tuple(address), length)
2024-02-10 17:06:30 +00:00
self.sock_thread.setDaemon(True)
2024-01-27 16:56:24 +00:00
self.sock_thread.start()
2024-02-17 17:05:21 +00:00
def get_raw(self):
2024-02-03 15:58:24 +00:00
if len(self.queue) == 0:
2024-01-27 16:56:24 +00:00
return []
with self.queue_lock:
queue = self.queue
self.queue = []
return queue
2024-02-17 17:05:21 +00:00
def get(self):
if len(self.queue) == 0:
return []
queue = []
with self.queue_lock:
for r in self.queue:
try:
queue.append([json.loads(r[0].decode()), r[1]])
except:
pass
self.queue.clear()
return queue
2024-01-27 16:56:24 +00:00
class SockThread(Thread):
def __init__(self, sock, address, length):
2024-02-03 15:58:24 +00:00
Thread.__init__(self)
2024-01-27 16:56:24 +00:00
self.sock = sock
2024-02-03 15:58:24 +00:00
self.length = length
2024-02-10 12:30:58 +00:00
self.sock.sock.bind(tuple(address))
2024-01-27 16:56:24 +00:00
def run(self):
while True:
2024-02-03 15:58:24 +00:00
r = self.sock.sock.recvfrom(self.length)
2024-02-10 12:30:58 +00:00
if NETTRACE:
print("Rec from", r[1], ":", r[0], file=sys.stderr)
2024-01-27 16:56:24 +00:00
with self.sock.queue_lock:
self.sock.queue.append(r)