tcp_message_io 0.1.0

A simple TCP server and client implementation to exchange messages
Documentation

tcp_message_io

A simple TCP client/server implementation for tokio that allows exchanging Vec<u8> messages, taking care of transforming the TCP stream into a message stream.

The wire format used by the library is the message plus a internal 8-byte header encoding the length of each message.

Client

Client usage is straightforward:

use tcp_message_io::TCPClient;

let client = TCPClient::connect("127.0.0.1", 12345).await.unwrap();
let request = vec![1, 2, 3];
let response = client.send(request).await.unwrap();

Server

Creating a server is very straightforward as well:

use tcp_message_io::{TCPServer, TCPResponse};

async fn echo_handler(request: Vec<u8>) -> Result<TCPResponse> {
    // This is an echo server :-) 
    let response = request;
    TCPResponse::Message(response)
}

TCPServer::new("127.0.0.1", 12345, echo_handler).listen().await;

TCPResponse can be one of the following:

  • TCPResponse::Message(response) to send a response message.
  • TCPResponse::CloseConnection to close the connection with the client. This will also send an empty response to the client.
  • TCPResponse::StopServer to shut the server down. This will also send an empty response to the client and close the connection.

In case the handler returns an error, the server will respond to the client with an empty message and keep listening for new messages. This mechanism is meant for unhandled errors, and to avoid errors on the client side or to leave the client hanging.

It's left as a responsibility of the user to build an error reporting mechanism on top of the transform if required.

Additionally, this crate supports stopping the server after a certain amount of inactivity (inactivity timeout):

TCPServer::new("127.0.0.1", 12345, echo_handler)
    .with_inactivity_timeout(60)  // Seconds 
    .listen()
    .await;

This feature is useful when building something like a worker node: a node might be orphaned for many reasons (network issues, master crashing, etc). In these cases it's useful to build a clean-up mechanism in the worker.