#socket-server #client-server #server #sockets #client #tcp

bitsock

使用方便的 Rust crate,用于创建 socket 服务器和客户端。

2 个版本

0.1.1 2021 年 11 月 24 日
0.1.0 2021 年 11 月 24 日

#6 in #socket-server

自定义许可

23KB
459

bitsock

Project Status: Active – The project has reached a stable, usable state and is being actively developed. Crates.io build GitHub Lines of code GitHub issues

使用方便的 Rust crate,用于创建 socket 服务器和客户端。

描述

此 crate 可用于各种用途的客户端与服务器应用程序,协议可以通过 数据包 定义,用户可以选择多种预定义的数据包类型,或者使用一个带有 u32 id 的通用数据包类型(见 Packet),以便创建自己的协议。

客户端处理方式简单:您可以为每次客户端连接指定一个 闭包,该闭包将在新 线程 上执行。

示例

客户端

use std::time::Duration;

use bitsock::{client::Client, Packet};

fn main() {
    // Create the client object.
    let mut client = Client::connect("0.0.0.0", 4444).unwrap();

    loop {
        // Try to send a packet containing just an i32.
        if let Err(_) = client.send(Packet::I32(5)) {
            eprintln!("Failed to send packet");
        } else {
            // If the packet can be sent, then listen to the server and wait for a Packet.
            let data = client.read().unwrap();

            // If the packet is a string, print it.
            if let Packet::String(s) = data {
                println!("Received String: {}", s);
            } else {
                // If the packet is another type, print the type.
                println!("Received Packet: {:?}", data);
            }
        }

        std::thread::sleep(Duration::from_secs(2));
    }
}

服务器

use bitsock::{server::ServerBuilder, Packet};

fn main() {
    // Create the server object and bind it to the 4444 port.
    let mut server = ServerBuilder::new()
        .port(4444)
        // Supply a client handler, this will be runned for every connected client (in a new thread).
        .client_handler(Box::new(|mut c| {
            // Print the client address once connected.
            println!("Client {} connected!", c.address());

            // Try to listen for Packet from the Client.
            while match c.read() {
                Ok(packet) => {
                    // Print the received packet
                    println!("Received: {:?}", packet);

                    // Send a string packet to the client.
                    c.send(Packet::String("Hello There!".to_string())).unwrap();
                    true
                }
                // If it fails, disconnect the Client and print the error.
                Err(e) => {
                    c.disconnect().unwrap();
                    println!("Client {} disconnected for {:?}!", c.address(), e);
                    false
                }
            } {}
        }))
        .build();

    server.run();
}

许可

LICENSE

依赖项

~245KB