Using MIO to build an async TCP client

Hi

I’m currently learning mio by implementing a basic asynchronous TCP client. This client reads input from stdin and sends it to a server, which then broadcasts the message to all connected clients. The server, however, uses the standard library’s blocking socket implementation rather than mio.

Implementation is here.

I’ve run into the following issue: when I write to the mio TcpStream, the data doesn’t get sent to the server immediately. Instead, the server only receives the data after the client disconnects, either by killing the process or manually disconnecting. I’m certain I’m missing something here. Could anyone point me in the right direction?

Attached some terminal output: server (top left), the rest are the connected clients

One more thing to add: the data received by the clients is often garbled and not what we’d expect. I suspect this might have to do with buffered reading or writing, but I haven’t been able to pinpoint the exact cause.

Copy/pasting my reply to your other post:

The server is probably waiting for a newline character. After all, if the client hasn't sent a newline yet, the server can't know if it has a full line yet.

Also, using write_all with mio is pretty much always incorrect. The write may succeed partially and then hit a WouldBlock error. In that case, you have to go back and wait for more mio events and continue the write when you get another write readiness event.

1 Like

NOTE: This was originally posted on MIO's discord channel - Link to conversation Discord

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.