py-libp2p/network/stream.py

61 lines
1.5 KiB
Python
Raw Normal View History

2018-10-15 13:52:25 +08:00
from .stream_interface import IStream
2018-10-21 01:42:16 +08:00
import asyncio
2018-10-15 13:52:25 +08:00
class Stream(IStream):
2018-10-22 00:55:45 +08:00
def __init__(self, peer_id):
2018-10-15 13:52:25 +08:00
self.peer_id = peer_id
2018-10-21 01:42:16 +08:00
peer_store = context.peer_store
peer_addr = peer_store.get(peer_id)
2018-10-22 01:35:56 +08:00
ip = peer_addr.get_protocol("ip4")
port = peer_addr.get_protocol("tcp")
2018-10-21 01:42:16 +08:00
# look up peer_id -> multiaddr in peer store
# parse multiaddr and set_protocol based on it
# open connection to multiaddr
# save connection to stream's state
self.open_connection(ip, port)
async def open_connection(self, ip, port):
self.reader, self.writer = await asyncio.open_connection(ip, port)
2018-10-15 13:52:25 +08:00
def protocol(self):
"""
:return: protocol id that stream runs on
"""
2018-10-21 01:42:16 +08:00
return self.protocol_id
2018-10-15 13:52:25 +08:00
def set_protocol(self, protocol_id):
"""
:param protocol_id: protocol id that stream runs on
:return: true if successful
"""
2018-10-21 01:42:16 +08:00
self.protocol_id = protocol_id
2018-10-15 13:52:25 +08:00
def read(self):
"""
read from stream
:return: bytes of input
"""
2018-10-22 01:35:56 +08:00
return self.reader.read(-1)
2018-10-15 13:52:25 +08:00
def write(self, _bytes):
"""
write to stream
:return: number of bytes written
"""
2018-10-22 01:35:56 +08:00
return self.write_to_stream(_bytes)
async def write_to_stream(self, _bytes):
to_return = self.writer.write(_bytes)
await self.writer.drain()
return to_return
2018-10-15 13:52:25 +08:00
def close(self):
"""
close stream
:return: true if successful
"""
2018-10-22 01:35:56 +08:00
self.writer.close()