2019-11-19 18:04:48 +08:00
|
|
|
from libp2p.io.abc import ReadWriteCloser
|
2019-11-19 14:01:12 +08:00
|
|
|
from libp2p.io.exceptions import IOException
|
2019-11-19 18:04:48 +08:00
|
|
|
|
2019-09-16 18:37:00 +08:00
|
|
|
from .exceptions import RawConnError
|
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-12-06 17:06:37 +08:00
|
|
|
stream: ReadWriteCloser
|
2019-10-25 01:28:42 +08:00
|
|
|
is_initiator: bool
|
2019-07-28 14:06:29 +08:00
|
|
|
|
2019-12-06 17:06:37 +08:00
|
|
|
def __init__(self, stream: ReadWriteCloser, initiator: bool) -> None:
|
|
|
|
self.stream = stream
|
2019-10-25 01:28:42 +08:00
|
|
|
self.is_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-10-24 14:41:10 +08:00
|
|
|
"""Raise `RawConnError` if the underlying connection breaks."""
|
2019-09-16 18:37:00 +08:00
|
|
|
try:
|
2019-12-06 17:06:37 +08:00
|
|
|
await self.stream.write(data)
|
2019-11-19 14:01:12 +08:00
|
|
|
except IOException as error:
|
2020-01-26 23:54:29 +08:00
|
|
|
raise RawConnError from error
|
2019-04-30 15:09:05 +08:00
|
|
|
|
2020-01-26 23:03:38 +08:00
|
|
|
async def read(self, n: int = None) -> bytes:
|
2019-08-20 18:09:36 +08:00
|
|
|
"""
|
2019-10-25 02:10:45 +08:00
|
|
|
Read up to ``n`` bytes from the underlying stream. This call is
|
2019-10-24 14:41:10 +08:00
|
|
|
delegated directly to the underlying ``self.reader``.
|
2019-09-19 22:19:36 +08:00
|
|
|
|
|
|
|
Raise `RawConnError` if the underlying connection breaks
|
2019-08-20 18:09:36 +08:00
|
|
|
"""
|
2019-09-16 18:37:00 +08:00
|
|
|
try:
|
2019-12-06 17:06:37 +08:00
|
|
|
return await self.stream.read(n)
|
2019-11-19 14:01:12 +08:00
|
|
|
except IOException as error:
|
2020-01-26 23:54:29 +08:00
|
|
|
raise RawConnError from error
|
2019-04-30 15:09:05 +08:00
|
|
|
|
2019-08-25 04:06:24 +08:00
|
|
|
async def close(self) -> None:
|
2019-12-06 17:06:37 +08:00
|
|
|
await self.stream.close()
|