11 releases
0.2.2 | Jan 28, 2024 |
---|---|
0.2.1 | Jan 27, 2024 |
0.1.1 | Jan 26, 2024 |
0.0.6 | Jan 9, 2024 |
0.0.2 | Dec 28, 2023 |
#2043 in Network programming
124 downloads per month
140KB
1.5K
SLoC
Tcp-Server
Read this in other languages: English, 简体中文.
Description
Convenient server-side TCP service. Also see tcp-client for client-side.
Based on tcp-handler.
With complete API document.
Usage
Add this to your Cargo.toml
:
[dependencies]
tcp-server = "~0.2"
Example
use tcp_server::{func_handler, Server};
use tcp_server::anyhow::anyhow;
use tcp_server::handler_base::FuncHandler;
use tcp_server::tcp_handler::bytes::{Buf, BufMut, BytesMut};
use tcp_server::tcp_handler::variable_len_reader::{VariableReader, VariableWriter};
use tcp_server::tokio::io::{AsyncReadExt, AsyncWriteExt};
struct MyServer;
impl Server for MyServer {
fn get_identifier(&self) -> &'static str {
"MyTcpApplication"
}
fn check_version(&self, version: &str) -> bool {
version == env!("CARGO_PKG_VERSION")
}
fn get_function<R, W>(&self, func: &str) -> Option<Box<dyn FuncHandler<R, W>>>
where R: AsyncReadExt + Unpin + Send, W: AsyncWriteExt + Unpin + Send {
match func {
// define your route here.
// example:
"hello" => Some(Box::new(HelloHandler)),
_ => None,
}
}
}
// define your method here.
// example:
func_handler!(HelloHandler, |stream| {
let mut reader = stream.recv().await?.reader();
if "hello server" != reader.read_string()? {
return Err(anyhow!("Invalid message."));
}
let mut writer = BytesMut::new().writer();
writer.write_string("hello client")?;
stream.send(&mut writer.into_inner()).await?;
Ok(())
});
#[tokio::main]
async fn main() {
MyServer.start().await.unwrap();
}
Version map
Versions map to tcp-client with the same protocol. (Recommended for use in conjunction, otherwise unexpected bugs may occur.)
client version | server version |
---|---|
>=0.1.0 | >=0.2.0 |
<0.1.0 | <0.2.0 |
Dependencies
~4–15MB
~184K SLoC