py-libp2p/libp2p/network/connection/raw_connection.py

38 lines
1.1 KiB
Python
Raw Normal View History

2018-11-11 22:56:44 +08:00
from .raw_connection_interface import IRawConnection
class RawConnection(IRawConnection):
2018-11-30 02:42:05 +08:00
def __init__(self, ip, port, reader, writer, initiator):
# pylint: disable=too-many-arguments
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
async def write(self, data):
self.writer.write(data)
self.writer.write("\n".encode())
await self.writer.drain()
async def read(self):
line = await self.reader.readline()
adjusted_line = line.decode().rstrip('\n')
# TODO: figure out a way to remove \n without going back and forth with
# encoding and decoding
return adjusted_line.encode()
def close(self):
self.writer.close()
2018-11-30 02:42:05 +08:00
def next_stream_id(self):
"""
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