bitsock
Safe Rust crate for creating socket servers and clients with ease.
Description
This crate can be used for Client <--> Server applications of every purpose, the protocol can be defined by the user thanks to Packets:
there are many type of specific purpose builtin Packets and one general purpose Packet type that can be identified with an u32 id (see Packet) so that you can create your own protocol.
The client handling has to be done in a simple way: you can specify a closure and that one will be executed on a new thread everytime a client connects.
Example
Client
use std::time::Duration;
use bitsock::{client::Client, Packet};
fn main() {
let mut client = Client::connect("0.0.0.0", 4444).unwrap();
loop {
if let Err(_) = client.send(Packet::I32(5)) {
eprintln!("Failed to send packet");
} else {
let data = client.read().unwrap();
if let Packet::String(s) = data {
println!("Received String: {}", s);
} else {
println!("Received Packet: {:?}", data);
}
}
std::thread::sleep(Duration::from_secs(2));
}
}
Server
use bitsock::{server::ServerBuilder, Packet};
fn main() {
let mut server = ServerBuilder::new()
.port(4444)
.client_handler(Box::new(|mut c| {
println!("Client {} connected!", c.address());
while match c.read() {
Ok(packet) => {
println!("Received: {:?}", packet);
c.send(Packet::String("Hello There!".to_string())).unwrap();
true
}
Err(e) => {
c.disconnect().unwrap();
println!("Client {} disconnected for {:?}!", c.address(), e);
false
}
} {}
}))
.build();
server.run();
}
License
See LICESE