srve

Crates.iosrve
lib.rssrve
version0.1.3
sourcesrc
created_at2021-03-21 04:54:12.088515
updated_at2021-03-22 01:33:25.113256
descriptionSimple API for creating server client communication with TCP streams.
homepage
repositoryhttps://github.com/eduardvercaemer/srve/
max_upload_size
id371579
size30,580
Eduard (eduardvercaemer)

documentation

https://docs.rs/srve/0.1.3/srve/

README

srve

srve allows you to create simple network communication in a server client model, the server holds a bunch of client connections, each with its own state, and you can communicate with them via messages.

The server uses a background thread to listen for new connections.

Client

To create a client, we specify the message we will be using.

#[derive(Serialize, Deserialize)]
struct Msg {
    Hello,
    Goodbye,
}

/* on main */
let c = Client::connect(addr)?;

then we can send and receive messages

c.send(Msg::Hello)?;
match c.recv()? {
    Msg::Hello => { ... }
    Msg::Goodbye => { ... }
}

we finish by closing the client

c.close()?;

Server

To create a server, we simply specify which messages we want to use, and which state to represent connections.

struct State {
    value: i32,
}

/* on main */
let s = Server<State, Msg>::bind(addr)?;

you can then setup callback functions for different purposes, such as handling new connections, or new messages, after that we can start the server.

s
    .on_connection(|conn| {})
    .on_message(|conn, msg| {
        // we can directly access the connection state
        conn.value += 1;
        // and also use connection methods
        conn.send(Msg::Goodbye).unwrap();
    })
    ( /* other callbacks, more in the docs */ )
    .run();

Examples

You can try the example code by running cargo run --example server and then cargo run --example client in a different (or multiple) terminal(s), then write commands to interact with the server.

There is also the broken.rs example, which I use to test how the server interacts with 'broken' clients, such as closing unexpectedly, or sending bad messages, etc.

Commit count: 0

cargo fmt