jsb-netgame/network.py

42 lines
1 KiB
Python
Raw Normal View History

2024-01-27 16:56:24 +00:00
import socket
from threading import Thread, Lock
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
def send(self, message, address):
2024-02-03 15:58:24 +00:00
if type(message) == str:
message = message.encode()
2024-01-27 16:56:24 +00:00
self.sock.sendto(message, address)
def listen(self, address, length=65535):
self.sock_thread = SockThread(self, address, length)
self.sock_thread.start()
2024-02-03 17:57:23 +00:00
def get(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
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-01-27 16:56:24 +00:00
self.sock.sock.bind(address)
def run(self):
while True:
2024-02-03 15:58:24 +00:00
r = self.sock.sock.recvfrom(self.length)
2024-01-27 16:56:24 +00:00
with self.sock.queue_lock:
self.sock.queue.append(r)