6 releases
0.2.3 | Nov 12, 2022 |
---|---|
0.2.2 | Nov 12, 2022 |
0.1.1 | Nov 11, 2022 |
#1269 in Encoding
47 downloads per month
9KB
165 lines
Just a simple TCP/UDP Message Communication wrapper.
Uses serde
to data serialization in bincode
format. Requires the type to derive serde::Serialize
for sending and serde:Deserialize
for receiving messages.
Consider the following enum:
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
enum Chat {
Connect,
Msg(String),
Close,
}
Receiving messages:
use std::{io, net::TcpListener};
use stmc::tcp;
fn main() -> io::Result<()> {
let listener = TcpListener::bind(("127.0.0.1", 8080))?;
'server: for mut stream in listener.incoming().flatten() {
loop {
let msg: Chat = tcp::read(&mut stream)?;
match msg {
Chat::Connect => println!("new user connect: {}", stream.ttl()?),
Chat::Msg(txt) => println!("new message from {}: {txt}", stream.ttl()?),
Chat::Close => break 'server,
}
}
}
Ok(())
}
Sending messages:
use serde::{Deserialize, Serialize};
use std::{io, net::TcpStream};
fn main() -> io::Result<()> {
let mut stream = TcpStream::connect(("127.0.0.1", 8080))?;
tcp::send(Chat::Connect, &mut stream)?;
tcp::send(Chat::Msg("hi".into()), &mut stream)?;
tcp::send(Chat::Close, &mut stream)?;
Ok(())
}
To use UDP protocol, just change from tcp
to udp
.
Dependencies
~0.6–1.2MB
~28K SLoC