Crates.io | srve |
lib.rs | srve |
version | 0.1.3 |
source | src |
created_at | 2021-03-21 04:54:12.088515 |
updated_at | 2021-03-22 01:33:25.113256 |
description | Simple API for creating server client communication with TCP streams. |
homepage | |
repository | https://github.com/eduardvercaemer/srve/ |
max_upload_size | |
id | 371579 |
size | 30,580 |
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.
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()?;
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();
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.