#tcp #sockets #net #cbsk #callback #data #server-client

cbsk_rayon

基于rayon的回调套接字工具

1个稳定版本

2.0.0 2024年8月21日

#6 in #cbsk

MIT/Apache

99KB
1.5K SLoC

cbsk是一个TCP数据回调工具,允许您专注于业务处理,无需担心TCP数据的读取、写入和拆分

支持Rust的最低版本

1.80.0

内部协议

cbsk内部有一个自定义的TCP数据验证协议,其协议逻辑如下

  1. 验证数据是否使用['c ',' b ','s',' k ']作为头部帧。如果不是,则丢弃数据。当然,您也可以自定义数据帧头部

  2. 获取头部帧后的第一个字节,表示数据长度的描述

  3. 根据数据长度的描述获取真实的数据长度

  4. 读取真实数据,如果有数据包占用,则拆分并调用回调。如果长度不足,则等待下一个TCP数据到达,直到长度一致

  5. 重复上述步骤,并从第一步开始

cbsk客户端示例

Cargo.toml

cbsk_base = "2.0.0"
cbsk_rayon = { version = "2.0.0", default-features = false, features = ["client"] }
fast_log = "1.7.3"

main.rs

use std::net::{IpAddr, SocketAddr};
use std::sync::LazyLock;
use std::thread;
use std::time::Duration;
use cbsk_base::log;
use cbsk_base::log::LevelFilter;
use cbsk_rayon::business::cbsk_write_trait::CbskWriteTrait;
use cbsk_rayon::client::callback::CbskClientCallBack;
use cbsk_rayon::client::CbskClient;

#[allow(non_upper_case_globals)]
static addr: LazyLock<SocketAddr> = LazyLock::new(|| { SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 8080) });

#[allow(non_upper_case_globals)]
pub static cbsk_client: LazyLock<CbskClient> = LazyLock::new(|| {
   CbskClient::new(Cb {}.into(), *addr, 1024)
});

pub fn main() {
   fast_log::init(fast_log::Config::new().level(LevelFilter::Info).console()).unwrap();
   cbsk_client.start();
   loop {
      thread::sleep(Duration::from_secs(10));
   }
}

struct Cb {}

impl CbskClientCallBack for Cb {
   fn conn(&self) {
      cbsk_client.send_bytes(b"hello server".to_vec());
   }

   fn recv(&self, bytes: Vec<u8>) {
      log::info!("bytes is {:?}",String::from_utf8(bytes));
      cbsk_client.send_bytes(b"hello server".to_vec());
   }
}

cbsk服务器示例

Cargo.toml

cbsk_base = "2.0.0"
cbsk_rayon = "2.0.0"
fast_log = "1.7.3"

main.rs

use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use cbsk_base::log;
use cbsk_base::log::LevelFilter;
use cbsk_rayon::business::cbsk_write_trait::CbskWriteTrait;
use cbsk_rayon::server::callback::CbskServerCallBack;
use cbsk_rayon::server::CbskServer;
use cbsk_rayon::server::client::CbskServerClient;

pub fn main() {
    fast_log::init(fast_log::config::Config::default().level(LevelFilter::Info).console()).unwrap();
    let addr = SocketAddr::new(IpAddr::from([127, 0, 0, 1]), 8080);
    let cbsk_server = CbskServer::new(Cb {}.into(), addr, 1024);
    cbsk_server.start();

    loop {
        thread::sleep(Duration::from_secs(10));
    }
}

struct Cb {}

impl CbskServerCallBack for Cb {
    fn recv(&self, bytes: Vec<u8>, client: Arc<CbskServerClient>) {
        log::info!("recv client data is {:?}", String::from_utf8(bytes));
        // thread::sleep(Duration::from_secs(3));
        client.send_bytes(b"hello client".to_vec());
    }
}

依赖项

~3–11MB
~112K SLoC