I've a python-based TCP server using asyncio, but it has an specific behavior: The TCP client (a PLC) connects to the app, but actually both the server or the client can start data flows. Once the data flow starts, it will be finished via specific-designed ACK messages.
The TCP server part is connected to a RMQ queue; on each new message, it will start a data flow with the PLC, wait response, then ACK each side and the flow is finished. On the PLC side, a flow can be started at any time (but if there is an ongoing flow, it will be just rejected), then the TCP server will do some processing, and then send response, the PLC sends ACK, the TCP server responds ACK, then the flow is finished.
The connection is kept always up.
I've implemented this using asyncio server and protocols, but I find the code to be overcomplexv and I don't like how bad it's adding new features or incrementing functionality.
I thought that I could be using the streams API instead, that seems much clearer, but I can't think if a way to handle both client-initiated requests through the reader, or start server requests to the client. I just wonder if this is possible?
So, after checking some possible options, I have this code that I can check it's working. Using a PLC simulator, connecting to the TCP port, I can either start a data flow from PC to PLC, and the other way around.
Using the code above, I can both use
writerandreaderto interact in both flows the way I was expecting.As stated, my main doubt comes on how to check the right way if there's any data pending. Also, by using the
asyncio.wait_forwith 500ms timeout, I think I can ensure it won't block or wait endlessly, but it might be a better way, too?