2019-07-28 14:06:29 +08:00
|
|
|
import asyncio
|
|
|
|
|
2018-11-11 22:56:44 +08:00
|
|
|
from .raw_connection_interface import IRawConnection
|
|
|
|
|
2019-08-01 06:00:12 +08:00
|
|
|
|
2018-11-11 22:56:44 +08:00
|
|
|
class RawConnection(IRawConnection):
|
|
|
|
|
2019-07-28 14:06:29 +08:00
|
|
|
conn_ip: str
|
|
|
|
conn_port: str
|
|
|
|
reader: asyncio.StreamReader
|
|
|
|
writer: asyncio.StreamWriter
|
|
|
|
_next_id: int
|
|
|
|
initiator: bool
|
|
|
|
|
2019-08-01 06:00:12 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
ip: str,
|
|
|
|
port: str,
|
|
|
|
reader: asyncio.StreamReader,
|
|
|
|
writer: asyncio.StreamWriter,
|
|
|
|
initiator: bool,
|
|
|
|
) -> None:
|
2018-11-11 22:56:44 +08:00
|
|
|
self.conn_ip = ip
|
|
|
|
self.conn_port = port
|
2018-11-12 01:17:12 +08:00
|
|
|
self.reader = reader
|
|
|
|
self.writer = writer
|
2018-11-30 02:42:05 +08:00
|
|
|
self._next_id = 0 if initiator else 1
|
|
|
|
self.initiator = initiator
|
2018-11-11 22:56:44 +08:00
|
|
|
|
2019-07-28 14:06:29 +08:00
|
|
|
async def write(self, data: bytes) -> None:
|
2019-04-30 15:09:05 +08:00
|
|
|
self.writer.write(data)
|
|
|
|
self.writer.write("\n".encode())
|
|
|
|
await self.writer.drain()
|
|
|
|
|
2019-07-28 14:06:29 +08:00
|
|
|
async def read(self) -> bytes:
|
2019-04-30 15:09:05 +08:00
|
|
|
line = await self.reader.readline()
|
2019-08-01 06:00:12 +08:00
|
|
|
adjusted_line = line.decode().rstrip("\n")
|
2019-04-30 15:09:05 +08:00
|
|
|
|
|
|
|
# TODO: figure out a way to remove \n without going back and forth with
|
|
|
|
# encoding and decoding
|
|
|
|
return adjusted_line.encode()
|
|
|
|
|
2019-07-28 14:06:29 +08:00
|
|
|
def close(self) -> None:
|
2018-11-12 06:15:55 +08:00
|
|
|
self.writer.close()
|
2018-11-30 02:42:05 +08:00
|
|
|
|
2019-07-28 14:06:29 +08:00
|
|
|
def next_stream_id(self) -> int:
|
2018-11-30 02:42:05 +08:00
|
|
|
"""
|
|
|
|
Get next available stream id
|
|
|
|
:return: next available stream id for the connection
|
|
|
|
"""
|
|
|
|
next_id = self._next_id
|
|
|
|
self._next_id += 2
|
|
|
|
return next_id
|