Changing transport's recv and send methods

Viewed 269

I am trying to implement a SCTP and asyncio based client using pysctp sockets. Ideally, I would like to do something like:

async def sctp_client():
    sock = sctp.sctpsocket_udp(socket.AF_INET)
    reader, writer = await asyncio.open_connection(sock=sock)
    writer.write(b'some data', ppid=5)
    await writer.drain()
    data = await reader.read(100)
    print(f'Received: {data.decode()}')
    writer.close()
    await writer.wait_closed()

In practice, there are two question:

  • Is there a way to pass a "transport factory" to open_connection or to loop.create_connection? I want the transport object contained by the streams to use sctp_recv instead of recv and sctp_send instead of send. Clearly the easiest way is to derive from the original transport class, but I couldn't find a good pythonic way to do it.
  • Is there a way to get a custom StreamWriter from open_connection? Obviously I could create my own one from the original, add a method to the original or just access the internal transport but these options are awfully ugly. The second best way I can think about is just to implement my own open_connection using the loop.create_connection.

Thanks a lot!

1 Answers

Looking at the source code, there is no way to provide a factory to asyncio.open_connection. That said, the code there isn't terribly complex. Note the last line of the docstring:

(If you want to customize the StreamReader and/or StreamReaderProtocol classes, just copy the code -- there's really nothing special here except some convenience.)

That's exactly what I'd recommend doing.

Related