repodnet 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- repod/__init__.py +62 -0
- repod/channel.py +214 -0
- repod/client.py +276 -0
- repod/constants.py +25 -0
- repod/protocol.py +124 -0
- repod/py.typed +0 -0
- repod/server.py +217 -0
- repodnet-0.1.0.dist-info/METADATA +202 -0
- repodnet-0.1.0.dist-info/RECORD +11 -0
- repodnet-0.1.0.dist-info/WHEEL +4 -0
- repodnet-0.1.0.dist-info/licenses/COPYING +165 -0
repod/__init__.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""repod -- Modern async networking library for multiplayer games.
|
|
2
|
+
|
|
3
|
+
A type-safe networking library built on asyncio and msgpack,
|
|
4
|
+
designed as a modern replacement for PodSixNet.
|
|
5
|
+
|
|
6
|
+
Server quick-start::
|
|
7
|
+
|
|
8
|
+
from repod import Server, Channel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MyChannel(Channel):
|
|
12
|
+
|
|
13
|
+
def Network_hello(self, data: dict) -> None:
|
|
14
|
+
self.send({"action": "response", "text": "Hi!"})
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MyServer(Server):
|
|
18
|
+
channel_class = MyChannel
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
MyServer(host="0.0.0.0", port=5071).launch()
|
|
22
|
+
|
|
23
|
+
Client quick-start::
|
|
24
|
+
|
|
25
|
+
import time
|
|
26
|
+
from repod import ConnectionListener
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MyClient(ConnectionListener):
|
|
30
|
+
|
|
31
|
+
def Network_connected(self, data: dict) -> None:
|
|
32
|
+
self.send({"action": "hello", "message": "Hello server!"})
|
|
33
|
+
|
|
34
|
+
def Network_response(self, data: dict) -> None:
|
|
35
|
+
print(data["text"])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
client = MyClient()
|
|
39
|
+
client.connect("localhost", 5071)
|
|
40
|
+
|
|
41
|
+
while True:
|
|
42
|
+
client.pump()
|
|
43
|
+
time.sleep(0.01)
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from repod.channel import Channel
|
|
47
|
+
from repod.client import Client, ConnectionListener
|
|
48
|
+
from repod.constants import DEFAULT_HOST, DEFAULT_PORT
|
|
49
|
+
from repod.protocol import decode, encode, read_message
|
|
50
|
+
from repod.server import Server
|
|
51
|
+
|
|
52
|
+
__all__ = [
|
|
53
|
+
"DEFAULT_HOST",
|
|
54
|
+
"DEFAULT_PORT",
|
|
55
|
+
"Channel",
|
|
56
|
+
"Client",
|
|
57
|
+
"ConnectionListener",
|
|
58
|
+
"Server",
|
|
59
|
+
"decode",
|
|
60
|
+
"encode",
|
|
61
|
+
"read_message",
|
|
62
|
+
]
|
repod/channel.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Network channel representing a single connection.
|
|
2
|
+
|
|
3
|
+
A :class:`Channel` represents one side of a TCP connection. On the
|
|
4
|
+
server side, each connected client gets its own ``Channel`` instance.
|
|
5
|
+
|
|
6
|
+
Subclass ``Channel`` and define ``Network_{action}`` methods to handle
|
|
7
|
+
specific message types::
|
|
8
|
+
|
|
9
|
+
class GameChannel(Channel):
|
|
10
|
+
|
|
11
|
+
def Network_chat(self, data: dict) -> None:
|
|
12
|
+
print(f"Chat: {data['message']}")
|
|
13
|
+
|
|
14
|
+
def Network_move(self, data: dict) -> None:
|
|
15
|
+
print(f"Player moved to {data['x']}, {data['y']}")
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import contextlib
|
|
22
|
+
import socket
|
|
23
|
+
from typing import TYPE_CHECKING, Any
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from repod.server import Server
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Channel[S: Server]:
|
|
30
|
+
"""Represents a single network connection.
|
|
31
|
+
|
|
32
|
+
Attributes:
|
|
33
|
+
addr: ``(host, port)`` tuple of the remote endpoint.
|
|
34
|
+
is_connected: Whether the connection is currently active.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
reader: asyncio.StreamReader,
|
|
40
|
+
writer: asyncio.StreamWriter,
|
|
41
|
+
server: S | None = None,
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Initialize a channel with asyncio stream reader/writer.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
reader: Async stream reader for incoming data.
|
|
47
|
+
writer: Async stream writer for outgoing data.
|
|
48
|
+
server: Optional reference to the parent
|
|
49
|
+
:class:`~repod.server.Server`.
|
|
50
|
+
"""
|
|
51
|
+
self._reader = reader
|
|
52
|
+
self._writer = writer
|
|
53
|
+
self._send_queue: asyncio.Queue[bytes] = asyncio.Queue()
|
|
54
|
+
self._receive_queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
|
|
55
|
+
self._closed = False
|
|
56
|
+
self._address: tuple[str, int] = writer.get_extra_info("peername")
|
|
57
|
+
self._server: S | None = server
|
|
58
|
+
self._buffer = b""
|
|
59
|
+
|
|
60
|
+
# Disable Nagle's algorithm for low-latency real-time communication.
|
|
61
|
+
sock: socket.socket | None = writer.get_extra_info("socket")
|
|
62
|
+
if sock is not None:
|
|
63
|
+
with contextlib.suppress(OSError):
|
|
64
|
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def addr(self) -> tuple[str, int]:
|
|
68
|
+
"""Remote address as a ``(host, port)`` tuple."""
|
|
69
|
+
return self._address
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def is_connected(self) -> bool:
|
|
73
|
+
"""Whether this channel is still connected."""
|
|
74
|
+
return not self._closed
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def server(self) -> S:
|
|
78
|
+
"""The parent :class:`~repod.server.Server` instance.
|
|
79
|
+
|
|
80
|
+
Raises:
|
|
81
|
+
RuntimeError: If the channel is not connected to a server.
|
|
82
|
+
"""
|
|
83
|
+
if self._server is None:
|
|
84
|
+
raise RuntimeError("Channel is not connected to a server")
|
|
85
|
+
return self._server
|
|
86
|
+
|
|
87
|
+
def send(self, data: dict[str, Any]) -> int:
|
|
88
|
+
"""Queue a message to be sent to the remote endpoint.
|
|
89
|
+
|
|
90
|
+
The dictionary is serialized with msgpack and framed with a
|
|
91
|
+
4-byte length prefix before being placed in the async send
|
|
92
|
+
queue.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
data: Message dictionary. Should contain an ``action`` key
|
|
96
|
+
to identify the message type on the receiver side.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
Number of bytes queued, or ``0`` if disconnected.
|
|
100
|
+
"""
|
|
101
|
+
if self._closed:
|
|
102
|
+
return 0
|
|
103
|
+
|
|
104
|
+
from repod.protocol import encode
|
|
105
|
+
|
|
106
|
+
outgoing = encode(data)
|
|
107
|
+
self._send_queue.put_nowait(outgoing)
|
|
108
|
+
return len(outgoing)
|
|
109
|
+
|
|
110
|
+
def on_connect(self) -> None:
|
|
111
|
+
"""Called when the connection is established.
|
|
112
|
+
|
|
113
|
+
Override in your subclass to run setup logic when a client
|
|
114
|
+
connects.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def on_close(self) -> None:
|
|
118
|
+
"""Called when the connection is closed.
|
|
119
|
+
|
|
120
|
+
Override in your subclass to run cleanup logic when a client
|
|
121
|
+
disconnects.
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
def on_error(self, error: Exception) -> None:
|
|
125
|
+
"""Called when a connection error occurs.
|
|
126
|
+
|
|
127
|
+
Override to implement custom error handling.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
error: The exception that was raised.
|
|
131
|
+
"""
|
|
132
|
+
print(f"Channel error: {error}")
|
|
133
|
+
|
|
134
|
+
def network_received(self, data: dict[str, Any]) -> None:
|
|
135
|
+
"""Fallback handler for messages with no specific handler.
|
|
136
|
+
|
|
137
|
+
Called when a message's ``action`` does not match any
|
|
138
|
+
``Network_{action}`` method. Override to handle unrecognized
|
|
139
|
+
messages.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
data: The received message dictionary.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
def _dispatch(self, data: dict[str, Any]) -> None:
|
|
146
|
+
"""Route a message to the matching ``Network_{action}`` method.
|
|
147
|
+
|
|
148
|
+
Falls back to :meth:`network_received` when no specific handler
|
|
149
|
+
is found.
|
|
150
|
+
|
|
151
|
+
Args:
|
|
152
|
+
data: Message dictionary with an ``action`` key.
|
|
153
|
+
"""
|
|
154
|
+
action = data.get("action", "")
|
|
155
|
+
method_name = f"Network_{action}"
|
|
156
|
+
handler = getattr(self, method_name, None)
|
|
157
|
+
if handler is not None:
|
|
158
|
+
handler(data)
|
|
159
|
+
else:
|
|
160
|
+
self.network_received(data)
|
|
161
|
+
|
|
162
|
+
async def _write_loop(self) -> None:
|
|
163
|
+
"""Continuously drain the send queue to the socket."""
|
|
164
|
+
try:
|
|
165
|
+
while not self._closed:
|
|
166
|
+
data = await self._send_queue.get()
|
|
167
|
+
if not data:
|
|
168
|
+
break
|
|
169
|
+
self._writer.write(data)
|
|
170
|
+
await self._writer.drain()
|
|
171
|
+
except Exception:
|
|
172
|
+
self._closed = True
|
|
173
|
+
|
|
174
|
+
async def _read_loop(self) -> None:
|
|
175
|
+
"""Continuously read from the socket and parse messages."""
|
|
176
|
+
from repod.constants import READ_BUFFER_SIZE
|
|
177
|
+
from repod.protocol import read_message
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
while not self._closed:
|
|
181
|
+
data = await self._reader.read(READ_BUFFER_SIZE)
|
|
182
|
+
if not data:
|
|
183
|
+
break
|
|
184
|
+
|
|
185
|
+
self._buffer += data
|
|
186
|
+
while True:
|
|
187
|
+
message, consumed = read_message(self._buffer)
|
|
188
|
+
if message is None:
|
|
189
|
+
break
|
|
190
|
+
self._buffer = self._buffer[consumed:]
|
|
191
|
+
if isinstance(message, dict) and "action" in message:
|
|
192
|
+
self._receive_queue.put_nowait(message)
|
|
193
|
+
except Exception:
|
|
194
|
+
pass
|
|
195
|
+
finally:
|
|
196
|
+
await self._handle_close()
|
|
197
|
+
|
|
198
|
+
async def _handle_close(self) -> None:
|
|
199
|
+
"""Handle connection teardown and cleanup."""
|
|
200
|
+
if self._closed:
|
|
201
|
+
return
|
|
202
|
+
|
|
203
|
+
self._closed = True
|
|
204
|
+
self._receive_queue.put_nowait({"action": "disconnected"})
|
|
205
|
+
self.on_close()
|
|
206
|
+
|
|
207
|
+
# Unblock a pending ``_write_loop`` waiting on the queue.
|
|
208
|
+
self._send_queue.put_nowait(b"")
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
self._writer.close()
|
|
212
|
+
await self._writer.wait_closed()
|
|
213
|
+
except Exception:
|
|
214
|
+
pass
|
repod/client.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
"""Async TCP client for connecting to a repod server.
|
|
2
|
+
|
|
3
|
+
Provides :class:`Client` (low-level) and :class:`ConnectionListener`
|
|
4
|
+
(high-level mixin) for client-side networking.
|
|
5
|
+
|
|
6
|
+
The client runs an asyncio event loop in a background daemon thread so
|
|
7
|
+
that the main game/application loop can remain fully synchronous.
|
|
8
|
+
|
|
9
|
+
Example::
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
from repod import ConnectionListener
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class GameClient(ConnectionListener):
|
|
16
|
+
|
|
17
|
+
def Network_connected(self, data: dict) -> None:
|
|
18
|
+
print("Connected!")
|
|
19
|
+
self.send({"action": "hello", "name": "Alice"})
|
|
20
|
+
|
|
21
|
+
def Network_chat(self, data: dict) -> None:
|
|
22
|
+
print(f"{data['name']}: {data['text']}")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
client = GameClient()
|
|
26
|
+
client.connect("localhost", 5071)
|
|
27
|
+
|
|
28
|
+
while True:
|
|
29
|
+
client.pump()
|
|
30
|
+
time.sleep(0.01)
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import asyncio
|
|
36
|
+
import contextlib
|
|
37
|
+
import queue
|
|
38
|
+
import socket
|
|
39
|
+
import threading
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
from repod.constants import DEFAULT_HOST, DEFAULT_PORT, READ_BUFFER_SIZE
|
|
43
|
+
from repod.protocol import encode, read_message
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class Client:
|
|
47
|
+
"""Low-level TCP client with a background asyncio event loop.
|
|
48
|
+
|
|
49
|
+
Runs asynchronous read/write loops in a daemon thread and exposes
|
|
50
|
+
thread-safe :meth:`send` / :meth:`close` methods for use from the
|
|
51
|
+
main thread.
|
|
52
|
+
|
|
53
|
+
Attributes:
|
|
54
|
+
address: ``(host, port)`` tuple for the remote server.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
host: str = DEFAULT_HOST,
|
|
60
|
+
port: int = DEFAULT_PORT,
|
|
61
|
+
) -> None:
|
|
62
|
+
"""Initialize the client.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
host: Server hostname or IP address.
|
|
66
|
+
port: Server port number.
|
|
67
|
+
"""
|
|
68
|
+
self.address: tuple[str, int] = (host, port)
|
|
69
|
+
self._reader: asyncio.StreamReader | None = None
|
|
70
|
+
self._writer: asyncio.StreamWriter | None = None
|
|
71
|
+
self._send_queue: queue.Queue[bytes] = queue.Queue()
|
|
72
|
+
self._receive_queue: queue.Queue[dict[str, Any]] = queue.Queue()
|
|
73
|
+
self._closed = True
|
|
74
|
+
self._buffer = b""
|
|
75
|
+
self._thread: threading.Thread | None = None
|
|
76
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
77
|
+
|
|
78
|
+
def start_background(self) -> None:
|
|
79
|
+
"""Start the network event loop in a daemon thread."""
|
|
80
|
+
if self._thread is None or not self._thread.is_alive():
|
|
81
|
+
self._thread = threading.Thread(target=self._run_loop, daemon=True)
|
|
82
|
+
self._thread.start()
|
|
83
|
+
|
|
84
|
+
def send(self, data: dict[str, Any]) -> int:
|
|
85
|
+
"""Queue a message for sending to the server.
|
|
86
|
+
|
|
87
|
+
Thread-safe -- call from your main game loop.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
data: Message dictionary. Should contain an ``action`` key.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
Number of bytes queued, or ``0`` if disconnected.
|
|
94
|
+
"""
|
|
95
|
+
if self._closed:
|
|
96
|
+
return 0
|
|
97
|
+
outgoing = encode(data)
|
|
98
|
+
self._send_queue.put(outgoing)
|
|
99
|
+
return len(outgoing)
|
|
100
|
+
|
|
101
|
+
def close(self) -> None:
|
|
102
|
+
"""Close the connection.
|
|
103
|
+
|
|
104
|
+
Safe to call from any thread. Subsequent calls are no-ops.
|
|
105
|
+
"""
|
|
106
|
+
if self._closed:
|
|
107
|
+
return
|
|
108
|
+
self._closed = True
|
|
109
|
+
self._receive_queue.put({"action": "disconnected"})
|
|
110
|
+
if self._writer:
|
|
111
|
+
self._writer.close()
|
|
112
|
+
|
|
113
|
+
def _run_loop(self) -> None:
|
|
114
|
+
"""Run the asyncio event loop in the background thread."""
|
|
115
|
+
self._loop = asyncio.new_event_loop()
|
|
116
|
+
asyncio.set_event_loop(self._loop)
|
|
117
|
+
try:
|
|
118
|
+
self._loop.run_until_complete(self._network_task())
|
|
119
|
+
except Exception as e:
|
|
120
|
+
print(f"Network thread error: {e}", flush=True)
|
|
121
|
+
finally:
|
|
122
|
+
self._loop.close()
|
|
123
|
+
|
|
124
|
+
async def _network_task(self) -> None:
|
|
125
|
+
"""Connect and spawn concurrent read/write loops."""
|
|
126
|
+
try:
|
|
127
|
+
self._reader, self._writer = await asyncio.open_connection(
|
|
128
|
+
*self.address,
|
|
129
|
+
)
|
|
130
|
+
sock: socket.socket | None = self._writer.get_extra_info("socket")
|
|
131
|
+
if sock is not None:
|
|
132
|
+
with contextlib.suppress(OSError):
|
|
133
|
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
|
134
|
+
|
|
135
|
+
self._closed = False
|
|
136
|
+
self._receive_queue.put({"action": "connected"})
|
|
137
|
+
self._receive_queue.put({"action": "socketConnect"})
|
|
138
|
+
except Exception as e:
|
|
139
|
+
self._receive_queue.put({"action": "error", "error": str(e)})
|
|
140
|
+
return
|
|
141
|
+
|
|
142
|
+
await asyncio.gather(self._read_loop(), self._write_loop())
|
|
143
|
+
|
|
144
|
+
async def _read_loop(self) -> None:
|
|
145
|
+
"""Read data from the socket and enqueue parsed messages."""
|
|
146
|
+
try:
|
|
147
|
+
while not self._closed and self._reader:
|
|
148
|
+
data = await self._reader.read(READ_BUFFER_SIZE)
|
|
149
|
+
if not data:
|
|
150
|
+
break
|
|
151
|
+
self._buffer += data
|
|
152
|
+
|
|
153
|
+
while True:
|
|
154
|
+
message, consumed = read_message(self._buffer)
|
|
155
|
+
if message is None:
|
|
156
|
+
break
|
|
157
|
+
self._buffer = self._buffer[consumed:]
|
|
158
|
+
if isinstance(message, dict) and "action" in message:
|
|
159
|
+
self._receive_queue.put(message)
|
|
160
|
+
except Exception:
|
|
161
|
+
pass
|
|
162
|
+
finally:
|
|
163
|
+
self.close()
|
|
164
|
+
|
|
165
|
+
async def _write_loop(self) -> None:
|
|
166
|
+
"""Drain the send queue to the socket."""
|
|
167
|
+
try:
|
|
168
|
+
while not self._closed and self._writer:
|
|
169
|
+
if not self._send_queue.empty():
|
|
170
|
+
while not self._send_queue.empty():
|
|
171
|
+
try:
|
|
172
|
+
data = self._send_queue.get_nowait()
|
|
173
|
+
self._writer.write(data)
|
|
174
|
+
except queue.Empty:
|
|
175
|
+
break
|
|
176
|
+
await self._writer.drain()
|
|
177
|
+
await asyncio.sleep(0.005)
|
|
178
|
+
except Exception:
|
|
179
|
+
self.close()
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class ConnectionListener:
|
|
183
|
+
"""High-level mixin for handling server messages synchronously.
|
|
184
|
+
|
|
185
|
+
Subclass this and define ``Network_{action}`` methods to handle
|
|
186
|
+
incoming messages. Call :meth:`pump` once per frame in your game
|
|
187
|
+
loop to process queued network events.
|
|
188
|
+
|
|
189
|
+
Example::
|
|
190
|
+
|
|
191
|
+
class MyClient(ConnectionListener):
|
|
192
|
+
|
|
193
|
+
def Network_connected(self, data: dict) -> None:
|
|
194
|
+
print("Connected to server!")
|
|
195
|
+
|
|
196
|
+
def Network_chat(self, data: dict) -> None:
|
|
197
|
+
print(f"Chat: {data['text']}")
|
|
198
|
+
|
|
199
|
+
client = MyClient()
|
|
200
|
+
client.connect("localhost", 5071)
|
|
201
|
+
|
|
202
|
+
while True:
|
|
203
|
+
client.pump()
|
|
204
|
+
time.sleep(0.01)
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
_connection: Client | None = None
|
|
208
|
+
|
|
209
|
+
def connect(
|
|
210
|
+
self,
|
|
211
|
+
host: str = DEFAULT_HOST,
|
|
212
|
+
port: int = DEFAULT_PORT,
|
|
213
|
+
) -> None:
|
|
214
|
+
"""Connect to a remote server.
|
|
215
|
+
|
|
216
|
+
Creates a :class:`Client` and starts its background network
|
|
217
|
+
thread.
|
|
218
|
+
|
|
219
|
+
Args:
|
|
220
|
+
host: Server hostname or IP address.
|
|
221
|
+
port: Server port number.
|
|
222
|
+
"""
|
|
223
|
+
self._connection = Client(host, port)
|
|
224
|
+
self._connection.start_background()
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def connection(self) -> Client | None:
|
|
228
|
+
"""The underlying :class:`Client` instance, or ``None``."""
|
|
229
|
+
return self._connection
|
|
230
|
+
|
|
231
|
+
def pump(self) -> None:
|
|
232
|
+
"""Process all pending network messages.
|
|
233
|
+
|
|
234
|
+
Call this once per frame in your game loop. Each queued message
|
|
235
|
+
is dispatched to the matching ``Network_{action}`` method, or to
|
|
236
|
+
:meth:`network_received` as a fallback.
|
|
237
|
+
"""
|
|
238
|
+
if self._connection is None:
|
|
239
|
+
return
|
|
240
|
+
|
|
241
|
+
while not self._connection._receive_queue.empty():
|
|
242
|
+
try:
|
|
243
|
+
data = self._connection._receive_queue.get_nowait()
|
|
244
|
+
except queue.Empty:
|
|
245
|
+
break
|
|
246
|
+
|
|
247
|
+
action = data.get("action", "")
|
|
248
|
+
method_name = f"Network_{action}"
|
|
249
|
+
handler = getattr(self, method_name, None)
|
|
250
|
+
if handler is not None:
|
|
251
|
+
handler(data)
|
|
252
|
+
else:
|
|
253
|
+
self.network_received(data)
|
|
254
|
+
|
|
255
|
+
def send(self, data: dict[str, Any]) -> int:
|
|
256
|
+
"""Send a message to the server.
|
|
257
|
+
|
|
258
|
+
Args:
|
|
259
|
+
data: Message dictionary. Should contain an ``action`` key.
|
|
260
|
+
|
|
261
|
+
Returns:
|
|
262
|
+
Number of bytes queued, or ``0`` if not connected.
|
|
263
|
+
"""
|
|
264
|
+
if self._connection is None:
|
|
265
|
+
return 0
|
|
266
|
+
return self._connection.send(data)
|
|
267
|
+
|
|
268
|
+
def network_received(self, data: dict[str, Any]) -> None:
|
|
269
|
+
"""Fallback handler for unrecognized message actions.
|
|
270
|
+
|
|
271
|
+
Override to handle messages that don't match any
|
|
272
|
+
``Network_{action}`` method.
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
data: The received message dictionary.
|
|
276
|
+
"""
|
repod/constants.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Network configuration constants.
|
|
2
|
+
|
|
3
|
+
Default values used throughout the repod networking library.
|
|
4
|
+
|
|
5
|
+
Example::
|
|
6
|
+
|
|
7
|
+
from repod.constants import DEFAULT_HOST, DEFAULT_PORT
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import Final
|
|
11
|
+
|
|
12
|
+
DEFAULT_HOST: Final[str] = "127.0.0.1"
|
|
13
|
+
"""Default hostname for connections (localhost)."""
|
|
14
|
+
|
|
15
|
+
DEFAULT_PORT: Final[int] = 5071
|
|
16
|
+
"""Default port for connections."""
|
|
17
|
+
|
|
18
|
+
HEADER_SIZE: Final[int] = 4
|
|
19
|
+
"""Size in bytes of the message length header."""
|
|
20
|
+
|
|
21
|
+
HEADER_FORMAT: Final[str] = ">I"
|
|
22
|
+
"""Struct format for the header (big-endian unsigned int)."""
|
|
23
|
+
|
|
24
|
+
READ_BUFFER_SIZE: Final[int] = 4096
|
|
25
|
+
"""Buffer size in bytes for reading from sockets."""
|
repod/protocol.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Message serialization protocol.
|
|
2
|
+
|
|
3
|
+
Handles encoding and decoding of network messages using msgpack
|
|
4
|
+
serialization with length-prefix framing.
|
|
5
|
+
|
|
6
|
+
Message format::
|
|
7
|
+
|
|
8
|
+
┌──────────────┬────────────────────────┐
|
|
9
|
+
│ 4 bytes │ N bytes │
|
|
10
|
+
│ length (BE) │ msgpack payload │
|
|
11
|
+
└──────────────┴────────────────────────┘
|
|
12
|
+
|
|
13
|
+
This framing method is efficient (O(1) boundary detection), safe
|
|
14
|
+
(no delimiter collision risk), and standard (used by Kafka, Redis,
|
|
15
|
+
Protocol Buffers, etc.).
|
|
16
|
+
|
|
17
|
+
Example::
|
|
18
|
+
|
|
19
|
+
>>> from repod.protocol import encode, decode
|
|
20
|
+
>>> data = {"action": "chat", "message": "Hello!"}
|
|
21
|
+
>>> encoded = encode(data)
|
|
22
|
+
>>> decoded = decode(encoded[4:]) # skip the 4-byte header
|
|
23
|
+
>>> decoded
|
|
24
|
+
{'action': 'chat', 'message': 'Hello!'}
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import struct
|
|
30
|
+
from typing import cast
|
|
31
|
+
|
|
32
|
+
import msgpack
|
|
33
|
+
|
|
34
|
+
from repod.constants import HEADER_FORMAT, HEADER_SIZE
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def encode(data: dict) -> bytes:
|
|
38
|
+
"""Encode a dictionary as a length-prefixed message frame.
|
|
39
|
+
|
|
40
|
+
The message is serialized with msgpack and prefixed with a 4-byte
|
|
41
|
+
big-endian length header.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
data: Dictionary containing the message data. Can include any
|
|
45
|
+
msgpack-serializable types (dict, list, str, int, float,
|
|
46
|
+
bool, None).
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
The encoded message with its 4-byte length prefix.
|
|
50
|
+
|
|
51
|
+
Raises:
|
|
52
|
+
TypeError: If *data* contains non-serializable types.
|
|
53
|
+
|
|
54
|
+
Example::
|
|
55
|
+
|
|
56
|
+
>>> encoded = encode({"action": "ping", "count": 5})
|
|
57
|
+
>>> len(encoded) > 4 # includes the 4-byte header
|
|
58
|
+
True
|
|
59
|
+
"""
|
|
60
|
+
packed = cast(bytes, msgpack.packb(data, use_bin_type=True))
|
|
61
|
+
length = struct.pack(HEADER_FORMAT, len(packed))
|
|
62
|
+
return length + packed
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def decode(data: bytes) -> dict:
|
|
66
|
+
"""Decode msgpack-serialized bytes into a dictionary.
|
|
67
|
+
|
|
68
|
+
Note:
|
|
69
|
+
This expects raw msgpack data, **not** a full length-prefixed
|
|
70
|
+
frame. Use :func:`read_message` for stream-based decoding.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
data: Raw msgpack-serialized bytes.
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
The decoded message dictionary.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
msgpack.UnpackException: If *data* is not valid msgpack.
|
|
80
|
+
|
|
81
|
+
Example::
|
|
82
|
+
|
|
83
|
+
>>> import msgpack
|
|
84
|
+
>>> raw = msgpack.packb({"action": "hello"})
|
|
85
|
+
>>> decode(raw)
|
|
86
|
+
{'action': 'hello'}
|
|
87
|
+
"""
|
|
88
|
+
return msgpack.unpackb(data, raw=False)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def read_message(stream: bytes) -> tuple[dict | None, int]:
|
|
92
|
+
"""Read a complete message from a byte stream.
|
|
93
|
+
|
|
94
|
+
Implements length-prefix framing to extract complete messages from
|
|
95
|
+
a potentially partial byte buffer.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
stream: Byte buffer that may contain partial or complete
|
|
99
|
+
messages.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
A ``(message, bytes_consumed)`` tuple. If the stream does not
|
|
103
|
+
yet contain a full message, returns ``(None, 0)``.
|
|
104
|
+
|
|
105
|
+
Example::
|
|
106
|
+
|
|
107
|
+
>>> frame = encode({"action": "test"})
|
|
108
|
+
>>> msg, consumed = read_message(frame)
|
|
109
|
+
>>> msg
|
|
110
|
+
{'action': 'test'}
|
|
111
|
+
>>> consumed == len(frame)
|
|
112
|
+
True
|
|
113
|
+
"""
|
|
114
|
+
if len(stream) < HEADER_SIZE:
|
|
115
|
+
return None, 0
|
|
116
|
+
|
|
117
|
+
length: int = struct.unpack(HEADER_FORMAT, stream[:HEADER_SIZE])[0]
|
|
118
|
+
total_size = HEADER_SIZE + length
|
|
119
|
+
|
|
120
|
+
if len(stream) < total_size:
|
|
121
|
+
return None, 0
|
|
122
|
+
|
|
123
|
+
payload = stream[HEADER_SIZE:total_size]
|
|
124
|
+
return msgpack.unpackb(payload, raw=False), total_size
|
repod/py.typed
ADDED
|
File without changes
|
repod/server.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Async TCP server for multiplayer games.
|
|
2
|
+
|
|
3
|
+
The :class:`Server` manages multiple client connections, creating a
|
|
4
|
+
:class:`~repod.channel.Channel` instance for each one. It can run in
|
|
5
|
+
the main thread or in a background daemon thread for host/client P2P
|
|
6
|
+
setups.
|
|
7
|
+
|
|
8
|
+
Example::
|
|
9
|
+
|
|
10
|
+
class GameChannel(Channel):
|
|
11
|
+
|
|
12
|
+
def Network_chat(self, data: dict) -> None:
|
|
13
|
+
self.server.send_to_all(
|
|
14
|
+
{"action": "chat", "text": data["text"]}
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class GameServer(Server):
|
|
19
|
+
channel_class = GameChannel
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
GameServer(host="0.0.0.0", port=5071).launch()
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import asyncio
|
|
28
|
+
import threading
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from repod.channel import Channel
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Server[C: Channel]:
|
|
35
|
+
"""Async TCP server that manages client channels.
|
|
36
|
+
|
|
37
|
+
Attributes:
|
|
38
|
+
host: Hostname or IP address the server is bound to.
|
|
39
|
+
port: Port number the server is listening on.
|
|
40
|
+
channels: List of currently connected client channels.
|
|
41
|
+
channel_class: The :class:`Channel` subclass instantiated for
|
|
42
|
+
each new connection. Must be set in your subclass.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
channel_class: type[C]
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
host: str = "127.0.0.1",
|
|
50
|
+
port: int = 5071,
|
|
51
|
+
) -> None:
|
|
52
|
+
"""Initialize the server.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
host: Hostname or IP to bind to. Use ``"0.0.0.0"`` for all
|
|
56
|
+
interfaces.
|
|
57
|
+
port: Port number to listen on.
|
|
58
|
+
"""
|
|
59
|
+
self.host = host
|
|
60
|
+
self.port = port
|
|
61
|
+
self.channels: list[C] = []
|
|
62
|
+
self._tcp_server: asyncio.Server | None = None
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def address(self) -> tuple[str, int]:
|
|
66
|
+
"""Server bind address as a ``(host, port)`` tuple."""
|
|
67
|
+
return (self.host, self.port)
|
|
68
|
+
|
|
69
|
+
async def start(self) -> None:
|
|
70
|
+
"""Start accepting connections.
|
|
71
|
+
|
|
72
|
+
Binds to ``host:port`` and begins listening for incoming TCP
|
|
73
|
+
connections.
|
|
74
|
+
"""
|
|
75
|
+
self._tcp_server = await asyncio.start_server(
|
|
76
|
+
self._handle_client,
|
|
77
|
+
self.host,
|
|
78
|
+
self.port,
|
|
79
|
+
)
|
|
80
|
+
addr = self._tcp_server.sockets[0].getsockname()
|
|
81
|
+
print(f"Server started on {addr[0]}:{addr[1]}")
|
|
82
|
+
|
|
83
|
+
async def run(self) -> None:
|
|
84
|
+
"""Run the server forever.
|
|
85
|
+
|
|
86
|
+
Blocks until the server is stopped or the task is cancelled.
|
|
87
|
+
"""
|
|
88
|
+
await asyncio.Future()
|
|
89
|
+
|
|
90
|
+
def launch(self) -> None:
|
|
91
|
+
"""Start the server and block forever.
|
|
92
|
+
|
|
93
|
+
Convenience wrapper that hides asyncio boilerplate. Equivalent
|
|
94
|
+
to calling :meth:`start` then :meth:`run` inside
|
|
95
|
+
``asyncio.run()``. Handles ``KeyboardInterrupt`` gracefully.
|
|
96
|
+
|
|
97
|
+
Example::
|
|
98
|
+
|
|
99
|
+
GameServer(host="0.0.0.0", port=5071).launch()
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
async def _main() -> None:
|
|
103
|
+
await self.start()
|
|
104
|
+
try:
|
|
105
|
+
await self.run()
|
|
106
|
+
except asyncio.CancelledError:
|
|
107
|
+
pass
|
|
108
|
+
finally:
|
|
109
|
+
await self.stop()
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
asyncio.run(_main())
|
|
113
|
+
except KeyboardInterrupt:
|
|
114
|
+
print("\nServer stopped.")
|
|
115
|
+
|
|
116
|
+
async def stop(self) -> None:
|
|
117
|
+
"""Stop the server and disconnect all clients."""
|
|
118
|
+
for channel in self.channels[:]:
|
|
119
|
+
await channel._handle_close()
|
|
120
|
+
if self._tcp_server:
|
|
121
|
+
self._tcp_server.close()
|
|
122
|
+
await self._tcp_server.wait_closed()
|
|
123
|
+
|
|
124
|
+
def start_background(self) -> threading.Thread:
|
|
125
|
+
"""Start the server in a daemon background thread.
|
|
126
|
+
|
|
127
|
+
Useful for *Host Game* scenarios where the main thread needs to
|
|
128
|
+
remain free for the game loop or UI.
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
The :class:`threading.Thread` running the server.
|
|
132
|
+
"""
|
|
133
|
+
thread = threading.Thread(target=self._run_in_thread, daemon=True)
|
|
134
|
+
thread.start()
|
|
135
|
+
return thread
|
|
136
|
+
|
|
137
|
+
def on_connect(self, channel: C, addr: tuple[str, int]) -> None:
|
|
138
|
+
"""Called when a new client connects.
|
|
139
|
+
|
|
140
|
+
Override to run per-client setup (e.g. add to a player list).
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
channel: The newly created channel for this client.
|
|
144
|
+
addr: ``(host, port)`` of the remote client.
|
|
145
|
+
"""
|
|
146
|
+
|
|
147
|
+
def on_disconnect(self, channel: C) -> None:
|
|
148
|
+
"""Called when a client disconnects.
|
|
149
|
+
|
|
150
|
+
Override to run per-client cleanup.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
channel: The channel that disconnected.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
def send_to_all(self, data: dict[str, Any]) -> None:
|
|
157
|
+
"""Broadcast a message to every connected client.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
data: Message dictionary to send to all channels.
|
|
161
|
+
"""
|
|
162
|
+
for channel in self.channels:
|
|
163
|
+
channel.send(data)
|
|
164
|
+
|
|
165
|
+
def _run_in_thread(self) -> None:
|
|
166
|
+
"""Create a new event loop and run the server inside it."""
|
|
167
|
+
loop = asyncio.new_event_loop()
|
|
168
|
+
asyncio.set_event_loop(loop)
|
|
169
|
+
loop.run_until_complete(self.start())
|
|
170
|
+
try:
|
|
171
|
+
loop.run_until_complete(self.run())
|
|
172
|
+
except Exception as e:
|
|
173
|
+
print(f"Background server error: {e}")
|
|
174
|
+
finally:
|
|
175
|
+
loop.run_until_complete(self.stop())
|
|
176
|
+
loop.close()
|
|
177
|
+
|
|
178
|
+
async def _handle_client(
|
|
179
|
+
self,
|
|
180
|
+
reader: asyncio.StreamReader,
|
|
181
|
+
writer: asyncio.StreamWriter,
|
|
182
|
+
) -> None:
|
|
183
|
+
"""Handle a newly connected client."""
|
|
184
|
+
channel = self.channel_class(reader, writer, server=self)
|
|
185
|
+
self.channels.append(channel)
|
|
186
|
+
|
|
187
|
+
channel.send({"action": "connected"})
|
|
188
|
+
channel.on_connect()
|
|
189
|
+
self.on_connect(channel, writer.get_extra_info("peername"))
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
await asyncio.gather(
|
|
193
|
+
channel._read_loop(),
|
|
194
|
+
channel._write_loop(),
|
|
195
|
+
self._process_loop(channel),
|
|
196
|
+
)
|
|
197
|
+
except Exception as e:
|
|
198
|
+
channel.on_error(e)
|
|
199
|
+
finally:
|
|
200
|
+
await self._remove_channel(channel)
|
|
201
|
+
|
|
202
|
+
async def _process_loop(self, channel: C) -> None:
|
|
203
|
+
"""Drain the channel's receive queue and dispatch messages."""
|
|
204
|
+
try:
|
|
205
|
+
while not channel._closed:
|
|
206
|
+
data = await channel._receive_queue.get()
|
|
207
|
+
if data.get("action") == "disconnected":
|
|
208
|
+
break
|
|
209
|
+
channel._dispatch(data)
|
|
210
|
+
except Exception:
|
|
211
|
+
pass
|
|
212
|
+
|
|
213
|
+
async def _remove_channel(self, channel: C) -> None:
|
|
214
|
+
"""Remove a channel and notify via :meth:`on_disconnect`."""
|
|
215
|
+
if channel in self.channels:
|
|
216
|
+
self.channels.remove(channel)
|
|
217
|
+
self.on_disconnect(channel)
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: repodnet
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Modern async networking library for multiplayer games
|
|
5
|
+
Project-URL: Homepage, https://github.com/Walkercito/repod
|
|
6
|
+
Project-URL: Repository, https://github.com/Walkercito/repod
|
|
7
|
+
Project-URL: Documentation, https://github.com/Walkercito/repod/blob/main/docs/DOCS.md
|
|
8
|
+
Project-URL: Issues, https://github.com/Walkercito/repod/issues
|
|
9
|
+
Author-email: Walkercito <walekrcitoliver@gmail.com>
|
|
10
|
+
License-Expression: LGPL-3.0-or-later
|
|
11
|
+
License-File: COPYING
|
|
12
|
+
Keywords: async,gamedev,msgpack,multiplayer,networking
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Games/Entertainment
|
|
21
|
+
Classifier: Topic :: Internet
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
23
|
+
Classifier: Topic :: System :: Networking
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.12
|
|
26
|
+
Requires-Dist: msgpack>=1.0.0
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# repod -- multiplayer networking library for Python games
|
|
30
|
+
|
|
31
|
+
[](https://www.python.org/)
|
|
32
|
+
[](https://www.gnu.org/licenses/lgpl-3.0)
|
|
33
|
+
[](https://github.com/astral-sh/ruff)
|
|
34
|
+
[](https://msgpack.org/)
|
|
35
|
+
[](https://docs.python.org/3/library/asyncio.html)
|
|
36
|
+
|
|
37
|
+
repod is a networking library designed to make it easy to write multiplayer games in Python. It uses `asyncio` and `msgpack` to asynchronously serialize network events and arbitrary data structures, and delivers them to your high-level classes through simple callback methods.
|
|
38
|
+
|
|
39
|
+
It is a modernized fork of [PodSixNet](https://github.com/chr15m/PodSixNet). Same ideas -- channels, action-based message dispatch, synchronous pump loops -- but rebuilt from scratch for Python 3.12+ with async I/O, binary msgpack serialization, and full type annotations. PodSixNet was built on `asyncore`, which was removed in Python 3.12; repod is the drop-in replacement.
|
|
40
|
+
|
|
41
|
+
Each class within your game client which wants to receive network events subclasses `ConnectionListener` and implements `Network_*` methods to catch specific events from the server. You don't have to wait for buffers to fill, or check sockets for waiting data or anything like that -- just call `client.pump()` once per game loop and the library handles everything else, passing off events to your listener. Sending data back to the server is just as easy with `client.send(mydata)`. On the server side, events are propagated to `Network_*` callbacks on your `Channel` subclass, and data is sent back to clients with `channel.send(mydata)`.
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install repod
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Or with [uv](https://docs.astral.sh/uv/):
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
uv add repod
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Examples
|
|
56
|
+
|
|
57
|
+
Chat example:
|
|
58
|
+
|
|
59
|
+
- `python examples/chat_server.py`
|
|
60
|
+
- and a couple of instances of `python examples/chat_client.py`
|
|
61
|
+
|
|
62
|
+
Whiteboard example (requires pygame-ce):
|
|
63
|
+
|
|
64
|
+
- `python examples/whiteboard_server.py`
|
|
65
|
+
- and a couple of instances of `python examples/whiteboard_client.py`
|
|
66
|
+
|
|
67
|
+
LagTime example (measures round-trip time from server to client):
|
|
68
|
+
|
|
69
|
+
- `python examples/lag_time_server.py`
|
|
70
|
+
- and a couple of instances of `python examples/lag_time_client.py`
|
|
71
|
+
|
|
72
|
+
## Quick start -- Server
|
|
73
|
+
|
|
74
|
+
You need to subclass two classes to make your own server. Each time a client connects, a new `Channel` instance is created, so you subclass `Channel` to make your server-side representation of a client:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from repod import Channel
|
|
78
|
+
|
|
79
|
+
class ClientChannel(Channel):
|
|
80
|
+
|
|
81
|
+
def network_received(self, data: dict) -> None:
|
|
82
|
+
print(data)
|
|
83
|
+
|
|
84
|
+
def Network_myaction(self, data: dict) -> None:
|
|
85
|
+
print("myaction:", data)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Whenever the client sends data, the `network_received()` fallback is called if no specific handler exists. The method `Network_myaction()` is only called if your data has an `"action"` key with a value of `"myaction"`. In other words, if the data looks like:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
{"action": "myaction", "blah": 123, ...}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Next, subclass `Server`:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from repod import Server
|
|
98
|
+
|
|
99
|
+
class MyServer(Server):
|
|
100
|
+
channel_class = ClientChannel
|
|
101
|
+
|
|
102
|
+
def on_connect(self, channel, addr):
|
|
103
|
+
print("new connection:", channel)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Set `channel_class` to the Channel subclass you created above. The `on_connect()` method is called whenever a new client connects.
|
|
107
|
+
|
|
108
|
+
To run the server, call `launch()`:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
MyServer(host="0.0.0.0", port=5071).launch()
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
That's it. One line. `launch()` handles the event loop internally and catches `Ctrl+C` for clean shutdown.
|
|
115
|
+
|
|
116
|
+
When you want to send data to a specific client, use the `send` method on the Channel:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
channel.send({"action": "hello", "message": "hello client!"})
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Quick start -- Client
|
|
123
|
+
|
|
124
|
+
To connect to your server, subclass `ConnectionListener`:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
import time
|
|
128
|
+
from repod import ConnectionListener
|
|
129
|
+
|
|
130
|
+
class MyClient(ConnectionListener):
|
|
131
|
+
|
|
132
|
+
def Network_connected(self, data: dict) -> None:
|
|
133
|
+
print("connected to the server")
|
|
134
|
+
|
|
135
|
+
def Network_error(self, data: dict) -> None:
|
|
136
|
+
print("error:", data["error"])
|
|
137
|
+
|
|
138
|
+
def Network_disconnected(self, data: dict) -> None:
|
|
139
|
+
print("disconnected from the server")
|
|
140
|
+
|
|
141
|
+
def Network_myaction(self, data: dict) -> None:
|
|
142
|
+
print("myaction:", data)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Network events are received by `Network_*` callback methods. Replace `*` with the value of the `"action"` key you want to catch. The `connected`, `disconnected`, and `error` events are sent automatically by repod.
|
|
146
|
+
|
|
147
|
+
Connect and pump:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
client = MyClient()
|
|
151
|
+
client.connect("localhost", 5071)
|
|
152
|
+
|
|
153
|
+
while True:
|
|
154
|
+
client.pump()
|
|
155
|
+
time.sleep(0.01)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Call `pump()` once per game loop and repod handles everything -- reading from the socket, deserializing, and dispatching to your `Network_*` methods. Sending data to the server:
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
client.send({"action": "myaction", "blah": 123, "things": [3, 4, 3, 4, 7]})
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
This works with any game framework that has a main loop: pygame, raylib, arcade, pyglet, etc. Just drop `pump()` into the loop.
|
|
165
|
+
|
|
166
|
+
## Documentation
|
|
167
|
+
|
|
168
|
+
Full tutorial and API reference: **[docs/DOCS.md](docs/DOCS.md)**
|
|
169
|
+
|
|
170
|
+
## Why not PodSixNet?
|
|
171
|
+
|
|
172
|
+
PodSixNet was great for its time, but:
|
|
173
|
+
|
|
174
|
+
- It's built on `asyncore`, which was **removed in Python 3.12**
|
|
175
|
+
- It uses `rencode` / custom delimiter-based framing (`\0---\0`), which is fragile with binary data
|
|
176
|
+
- It has no type annotations, no modern tooling support
|
|
177
|
+
- It is no longer maintained ([chr15m/PodSixNet#46](https://github.com/chr15m/PodSixNet/issues/46))
|
|
178
|
+
|
|
179
|
+
repod keeps the same simple API philosophy but replaces the internals:
|
|
180
|
+
|
|
181
|
+
- **asyncio** instead of asyncore
|
|
182
|
+
- **msgpack** with length-prefix framing instead of rencode with delimiter framing
|
|
183
|
+
- **Full type annotations** with PEP 695 generics (optional)
|
|
184
|
+
- **Python 3.12+** only -- no compatibility shims
|
|
185
|
+
|
|
186
|
+
## Development
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
uv sync --group dev
|
|
190
|
+
uv run ruff check .
|
|
191
|
+
uv run ruff format --check .
|
|
192
|
+
uv run ty check
|
|
193
|
+
uv run pytest tests/ -v
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## License
|
|
197
|
+
|
|
198
|
+
Copyright Walker Gonzales, 2025.
|
|
199
|
+
|
|
200
|
+
repod is licensed under the terms of the **LGPL v3.0** or later. See the [COPYING](COPYING) file for details.
|
|
201
|
+
|
|
202
|
+
This is the same license as [PodSixNet](https://github.com/chr15m/PodSixNet), from which repod is forked. In short: you can use repod in any project (commercial or otherwise), but if you modify the repod library code itself, you must make the modified source available.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
repod/__init__.py,sha256=3v-9I_VA5CTYebbqMQD2paMmMmkvS3IOuux0W87vIVA,1374
|
|
2
|
+
repod/channel.py,sha256=eEIVhJdqfhD7RPjTOlFihytTS6GvpRwlmRLHL9y1zbE,6749
|
|
3
|
+
repod/client.py,sha256=5eL9omBiXn7zmis-hk7K-LQg6BpRpen2fhV6atP34O0,8701
|
|
4
|
+
repod/constants.py,sha256=kP2Ig7eRBlez_1_eYrMcdGREocSaJ36RuEnHfSJK2_k,625
|
|
5
|
+
repod/protocol.py,sha256=Y764G3vyynKdGFl1xJ8AZlc8UIH3vBwrrz2-IGo-UJY,3562
|
|
6
|
+
repod/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
repod/server.py,sha256=qFBC7eKPkKZN0fszze8W3VRr1kjPvFtFIXldnL11Ltk,6530
|
|
8
|
+
repodnet-0.1.0.dist-info/METADATA,sha256=w8WeHYW14gXE6QIYYRace0slQzaYqBWGOXdD9fljjQA,8021
|
|
9
|
+
repodnet-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
10
|
+
repodnet-0.1.0.dist-info/licenses/COPYING,sha256=qFPC_-wXBXhyNA7uJCrk2Wy_K1IK4n2QPhsv7xpfnRw,7639
|
|
11
|
+
repodnet-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
GNU LESSER GENERAL PUBLIC LICENSE
|
|
2
|
+
Version 3, 29 June 2007
|
|
3
|
+
|
|
4
|
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
|
5
|
+
Everyone is permitted to copy and distribute verbatim copies
|
|
6
|
+
of this license document, but changing it is not allowed.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
This version of the GNU Lesser General Public License incorporates
|
|
10
|
+
the terms and conditions of version 3 of the GNU General Public
|
|
11
|
+
License, supplemented by the additional permissions listed below.
|
|
12
|
+
|
|
13
|
+
0. Additional Definitions.
|
|
14
|
+
|
|
15
|
+
As used herein, "this License" refers to version 3 of the GNU Lesser
|
|
16
|
+
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
|
17
|
+
General Public License.
|
|
18
|
+
|
|
19
|
+
"The Library" refers to a covered work governed by this License,
|
|
20
|
+
other than an Application or a Combined Work as defined below.
|
|
21
|
+
|
|
22
|
+
An "Application" is any work that makes use of an interface provided
|
|
23
|
+
by the Library, but which is not otherwise based on the Library.
|
|
24
|
+
Defining a subclass of a class defined by the Library is deemed a mode
|
|
25
|
+
of using an interface provided by the Library.
|
|
26
|
+
|
|
27
|
+
A "Combined Work" is a work produced by combining or linking an
|
|
28
|
+
Application with the Library. The particular version of the Library
|
|
29
|
+
with which the Combined Work was made is also called the "Linked
|
|
30
|
+
Version".
|
|
31
|
+
|
|
32
|
+
The "Minimal Corresponding Source" for a Combined Work means the
|
|
33
|
+
Corresponding Source for the Combined Work, excluding any source code
|
|
34
|
+
for portions of the Combined Work that, considered in isolation, are
|
|
35
|
+
based on the Application, and not on the Linked Version.
|
|
36
|
+
|
|
37
|
+
The "Corresponding Application Code" for a Combined Work means the
|
|
38
|
+
object code and/or source code for the Application, including any data
|
|
39
|
+
and utility programs needed for reproducing the Combined Work from the
|
|
40
|
+
Application, but excluding the System Libraries of the Combined Work.
|
|
41
|
+
|
|
42
|
+
1. Exception to Section 3 of the GNU GPL.
|
|
43
|
+
|
|
44
|
+
You may convey a covered work under sections 3 and 4 of this License
|
|
45
|
+
without being bound by section 3 of the GNU GPL.
|
|
46
|
+
|
|
47
|
+
2. Conveying Modified Versions.
|
|
48
|
+
|
|
49
|
+
If you modify a copy of the Library, and, in your modifications, a
|
|
50
|
+
facility refers to a function or data to be supplied by an Application
|
|
51
|
+
that uses the facility (other than as an argument passed when the
|
|
52
|
+
facility is invoked), then you may convey a copy of the modified
|
|
53
|
+
version:
|
|
54
|
+
|
|
55
|
+
a) under this License, provided that you make a good faith effort to
|
|
56
|
+
ensure that, in the event an Application does not supply the
|
|
57
|
+
function or data, the facility still operates, and performs
|
|
58
|
+
whatever part of its purpose remains meaningful, or
|
|
59
|
+
|
|
60
|
+
b) under the GNU GPL, with none of the additional permissions of
|
|
61
|
+
this License applicable to that copy.
|
|
62
|
+
|
|
63
|
+
3. Object Code Incorporating Material from Library Header Files.
|
|
64
|
+
|
|
65
|
+
The object code form of an Application may incorporate material from
|
|
66
|
+
a header file that is part of the Library. You may convey such object
|
|
67
|
+
code under terms of your choice, provided that, if the incorporated
|
|
68
|
+
material is not limited to numerical parameters, data structure
|
|
69
|
+
layouts and accessors, or small macros, inline functions and templates
|
|
70
|
+
(ten or fewer lines in length), you do both of the following:
|
|
71
|
+
|
|
72
|
+
a) Give prominent notice with each copy of the object code that the
|
|
73
|
+
Library is used in it and that the Library and its use are
|
|
74
|
+
covered by this License.
|
|
75
|
+
|
|
76
|
+
b) Accompany the object code with a copy of the GNU GPL and this license
|
|
77
|
+
document.
|
|
78
|
+
|
|
79
|
+
4. Combined Works.
|
|
80
|
+
|
|
81
|
+
You may convey a Combined Work under terms of your choice that,
|
|
82
|
+
taken together, effectively do not restrict modification of the
|
|
83
|
+
portions of the Library contained in the Combined Work and reverse
|
|
84
|
+
engineering for debugging such modifications, if you also do each of
|
|
85
|
+
the following:
|
|
86
|
+
|
|
87
|
+
a) Give prominent notice with each copy of the Combined Work that
|
|
88
|
+
the Library is used in it and that the Library and its use are
|
|
89
|
+
covered by this License.
|
|
90
|
+
|
|
91
|
+
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
|
92
|
+
document.
|
|
93
|
+
|
|
94
|
+
c) For a Combined Work that displays copyright notices during
|
|
95
|
+
execution, include the copyright notice for the Library among
|
|
96
|
+
these notices, as well as a reference directing the user to the
|
|
97
|
+
copies of the GNU GPL and this license document.
|
|
98
|
+
|
|
99
|
+
d) Do one of the following:
|
|
100
|
+
|
|
101
|
+
0) Convey the Minimal Corresponding Source under the terms of this
|
|
102
|
+
License, and the Corresponding Application Code in a form
|
|
103
|
+
suitable for, and under terms that permit, the user to
|
|
104
|
+
recombine or relink the Application with a modified version of
|
|
105
|
+
the Linked Version to produce a modified Combined Work, in the
|
|
106
|
+
manner specified by section 6 of the GNU GPL for conveying
|
|
107
|
+
Corresponding Source.
|
|
108
|
+
|
|
109
|
+
1) Use a suitable shared library mechanism for linking with the
|
|
110
|
+
Library. A suitable mechanism is one that (a) uses at run time
|
|
111
|
+
a copy of the Library already present on the user's computer
|
|
112
|
+
system, and (b) will operate properly with a modified version
|
|
113
|
+
of the Library that is interface-compatible with the Linked
|
|
114
|
+
Version.
|
|
115
|
+
|
|
116
|
+
e) Provide Installation Information, but only if you would otherwise
|
|
117
|
+
be required to provide such information under section 6 of the
|
|
118
|
+
GNU GPL, and only to the extent that such information is
|
|
119
|
+
necessary to install and execute a modified version of the
|
|
120
|
+
Combined Work produced by recombining or relinking the
|
|
121
|
+
Application with a modified version of the Linked Version. (If
|
|
122
|
+
you use option 4d0, the Installation Information must accompany
|
|
123
|
+
the Minimal Corresponding Source and Corresponding Application
|
|
124
|
+
Code. If you use option 4d1, you must provide the Installation
|
|
125
|
+
Information in the manner specified by section 6 of the GNU GPL
|
|
126
|
+
for conveying Corresponding Source.)
|
|
127
|
+
|
|
128
|
+
5. Combined Libraries.
|
|
129
|
+
|
|
130
|
+
You may place library facilities that are a work based on the
|
|
131
|
+
Library side by side in a single library together with other library
|
|
132
|
+
facilities that are not Applications and are not covered by this
|
|
133
|
+
License, and convey such a combined library under terms of your
|
|
134
|
+
choice, if you do both of the following:
|
|
135
|
+
|
|
136
|
+
a) Accompany the combined library with a copy of the same work based
|
|
137
|
+
on the Library, uncombined with any other library facilities,
|
|
138
|
+
conveyed under the terms of this License.
|
|
139
|
+
|
|
140
|
+
b) Give prominent notice with the combined library that part of it
|
|
141
|
+
is a work based on the Library, and explaining where to find the
|
|
142
|
+
accompanying uncombined form of the same work.
|
|
143
|
+
|
|
144
|
+
6. Revised Versions of the GNU Lesser General Public License.
|
|
145
|
+
|
|
146
|
+
The Free Software Foundation may publish revised and/or new versions
|
|
147
|
+
of the GNU Lesser General Public License from time to time. Such new
|
|
148
|
+
versions will be similar in spirit to the present version, but may
|
|
149
|
+
differ in detail to address new problems or concerns.
|
|
150
|
+
|
|
151
|
+
Each version is given a distinguishing version number. If the
|
|
152
|
+
Library as you received it specifies that a certain numbered version
|
|
153
|
+
of the GNU Lesser General Public License "or any later version"
|
|
154
|
+
applies to it, you have the option of following the terms and
|
|
155
|
+
conditions either of that published version or of any later version
|
|
156
|
+
published by the Free Software Foundation. If the Library as you
|
|
157
|
+
received it does not specify a version number of the GNU Lesser
|
|
158
|
+
General Public License, you may choose any version of the GNU Lesser
|
|
159
|
+
General Public License ever published by the Free Software Foundation.
|
|
160
|
+
|
|
161
|
+
If the Library as you received it specifies that a proxy can decide
|
|
162
|
+
whether future versions of the GNU Lesser General Public License shall
|
|
163
|
+
apply, that proxy's public statement of acceptance of any version is
|
|
164
|
+
permanent authorization for you to choose that version for the
|
|
165
|
+
Library.
|