Crate tcp_server
source ·Expand description
§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 |
Re-exports§
pub extern crate anyhow;
pub extern crate async_trait;
pub extern crate tcp_handler;
pub extern crate tokio;
Modules§
- Global configuration for this crate.
- The basic trait for handler.
- Some network utility functions.
Macros§
- Conveniently define a handler.
Traits§
- The basic trait for a server.