tcp-server

Crates.iotcp-server
lib.rstcp-server
version0.2.2
sourcesrc
created_at2023-12-28 07:07:25.259041
updated_at2024-01-28 05:02:12.980189
descriptionConvenient server-side TCP service. Based on tcp-handler.
homepage
repositoryhttps://github.com/xuxiaocheng0201/tcp-handler/tree/server
max_upload_size
id1082209
size45,636
(xuxiaocheng0201)

documentation

https://docs.rs/tcp-server/

README

Tcp-Server

Crate Crates.io License

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
Commit count: 73

cargo fmt