Add delim_encode and delim_read

- Add `StreamCommunicator` and `RawConnectionCommunicator`, read/write
messages with delim codec, with `IMuxedStream` and `IRawConnection`
respectively.
- Use it in `Multiselect` and `MultiselectClient`.
This commit is contained in:
mhchia
2019-08-15 23:31:26 +08:00
committed by Kevin Mai-Husan Chia
parent 8cd23abfe2
commit 86d4ce1da8
11 changed files with 74 additions and 64 deletions

View File

@ -1,8 +1,7 @@
from typing import Dict, Tuple
from libp2p.typing import NegotiableTransport, StreamHandlerFn, TProtocol
from libp2p.typing import StreamHandlerFn, TProtocol
from .multiselect_communicator import MultiselectCommunicator
from .multiselect_communicator_interface import IMultiselectCommunicator
from .multiselect_muxer_interface import IMultiselectMuxer
@ -31,7 +30,7 @@ class Multiselect(IMultiselectMuxer):
self.handlers[protocol] = handler
async def negotiate(
self, stream: NegotiableTransport
self, communicator: IMultiselectCommunicator
) -> Tuple[TProtocol, StreamHandlerFn]:
"""
Negotiate performs protocol selection
@ -39,8 +38,6 @@ class Multiselect(IMultiselectMuxer):
:return: selected protocol name, handler function
:raise Exception: negotiation failed exception
"""
# Create a communicator to handle all communication across the stream
communicator = MultiselectCommunicator(stream)
# Perform handshake to ensure multiselect protocol IDs match
await self.handshake(communicator)
@ -48,7 +45,7 @@ class Multiselect(IMultiselectMuxer):
# Read and respond to commands until a valid protocol ID is sent
while True:
# Read message
command = await communicator.read_stream_until_eof()
command = await communicator.read()
# Command is ls or a protocol
if command == "ls":
@ -78,7 +75,7 @@ class Multiselect(IMultiselectMuxer):
await communicator.write(MULTISELECT_PROTOCOL_ID)
# Read in the protocol ID from other party
handshake_contents = await communicator.read_stream_until_eof()
handshake_contents = await communicator.read()
# Confirm that the protocols are the same
if not validate_handshake(handshake_contents):