-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
105 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,3 @@ | ||
import imcpy.network.tcp | ||
import imcpy.network.udp | ||
import imcpy.network.utils |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
import asyncio | ||
import logging | ||
|
||
import imcpy | ||
|
||
logger = logging.getLogger('imcpy.tcp') | ||
|
||
|
||
class IMCProtocolTCPClientConnection: | ||
def __init__(self, name: str, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: | ||
self.name = name | ||
self.reader = reader | ||
self.writer = writer | ||
self._parser = imcpy.Parser() | ||
|
||
async def write_bytes(self, data: bytes): | ||
"""Write the bytes to the connected clients and flush buffer if necessary. | ||
:param data: The serialized IMC message to write. | ||
""" | ||
self.writer.write(data) | ||
await self.writer.drain() | ||
|
||
async def close(self): | ||
self.writer.close() | ||
await self.writer.wait_closed() | ||
|
||
async def handle_data(self, instance): | ||
"""Handle incoming data from the client.""" | ||
try: | ||
while True: | ||
data = await self.reader.read(4096) | ||
if not data: | ||
logger.error(f'Connection closed by peer ({self.name})') | ||
await self.close() | ||
return | ||
|
||
data_remaining = len(data) | ||
while data_remaining > 0: | ||
msg, parsed_bytes = self._parser.parse(data[-data_remaining:]) | ||
data_remaining -= parsed_bytes | ||
if msg is not None: | ||
# Log IMC message to file if enabled | ||
if instance.log_imc_fh and not instance.log_imc_fh.closed: | ||
instance.log_imc_fh.write(data) | ||
|
||
instance.post_message(msg) | ||
except ConnectionError as e: | ||
logger.error(f'Connection error ({self.name}): {e}') | ||
await self.close() | ||
|
||
|
||
class IMCProtocolTCPServer: | ||
def __init__(self, instance) -> None: | ||
self.instance = instance | ||
self._clients = set() | ||
|
||
async def on_connection(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter): | ||
logger.info(f'New connection from {writer.get_extra_info("peername")}') | ||
client = IMCProtocolTCPClientConnection(writer.get_extra_info('peername'), reader, writer) | ||
self._clients.add(client) | ||
await client.handle_data(self.instance) | ||
self._clients.remove(client) | ||
|
||
async def write_message(self, msg: imcpy.Message): | ||
"""Write message to all connected clients. | ||
:param msg: The IMC message to write. | ||
""" | ||
b = msg.serialize() | ||
for client in self._clients: | ||
await client.write_bytes(b) |