Crates.io | bitsock |
lib.rs | bitsock |
version | 0.1.1 |
source | src |
created_at | 2021-11-24 09:58:12.629377 |
updated_at | 2021-11-24 10:12:43.727136 |
description | Safe Rust crate for creating socket servers and clients with ease. |
homepage | |
repository | https://github.com/LolzDEV/bitsock |
max_upload_size | |
id | 486774 |
size | 29,706 |
Safe Rust crate for creating socket servers and clients with ease.
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.
Client
use std::time::Duration;
use bitsock::{client::Client, Packet};
fn main() {
// Create the client object.
let mut client = Client::connect("0.0.0.0", 4444).unwrap();
loop {
// Try to send a packet containing just an i32.
if let Err(_) = client.send(Packet::I32(5)) {
eprintln!("Failed to send packet");
} else {
// If the packet can be sent, then listen to the server and wait for a Packet.
let data = client.read().unwrap();
// If the packet is a string, print it.
if let Packet::String(s) = data {
println!("Received String: {}", s);
} else {
// If the packet is another type, print the type.
println!("Received Packet: {:?}", data);
}
}
std::thread::sleep(Duration::from_secs(2));
}
}
Server
use bitsock::{server::ServerBuilder, Packet};
fn main() {
// Create the server object and bind it to the 4444 port.
let mut server = ServerBuilder::new()
.port(4444)
// Supply a client handler, this will be runned for every connected client (in a new thread).
.client_handler(Box::new(|mut c| {
// Print the client address once connected.
println!("Client {} connected!", c.address());
// Try to listen for Packet from the Client.
while match c.read() {
Ok(packet) => {
// Print the received packet
println!("Received: {:?}", packet);
// Send a string packet to the client.
c.send(Packet::String("Hello There!".to_string())).unwrap();
true
}
// If it fails, disconnect the Client and print the error.
Err(e) => {
c.disconnect().unwrap();
println!("Client {} disconnected for {:?}!", c.address(), e);
false
}
} {}
}))
.build();
server.run();
}
See LICESE