#udp-server #async #gamedev #built #mind #ease #packet

packetz

轻松创建基于包的异步服务器,考虑到游戏开发。关注UDP支持,更多功能即将推出!

4个版本 (2个稳定版)

2.0.0 2023年7月1日
1.0.0 2023年6月30日
0.1.1 2023年6月30日
0.1.0 2023年6月30日

#14 in #mind

每月34次下载

ISC 许可证

17KB
330 代码行

Packetz

轻松创建基于包的异步服务器,考虑到游戏开发。关注UDP支持,更多功能即将推出!

基本用法

服务器

use packetz::{server::*, packet::*};

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    let server: Server<&str> = Server::bind("0.0.0.0:5515"); // The extra &str is the type of the argumet in `server::bind()`, so that server::bind is able to be a const fn.
    let listener: ServerListener = server.listen().await?;

    loop {
        let (
            mut connection,
            addr
        ) = listener.accept().await?;
        let _: tokio::task::JoinHandle<Result<(), std::io::Error>> = tokio::spawn(async move {
            'l: loop { // In a real world scenario we would check for errors on the `send` and `recv` methods, and break the loop if one is found, and disconnect the client without disconnecting all other clients.
                let msg = connection.recv().await?;
                connection.send(msg.body).await?;
                connection.disconnect(); // This is optional, as all it does is drop the PacketStream, and breaking the loop should automaticall drop it.
                break 'l;
            }
            Ok(())
        });
    }
}

客户端

use packetz::{client::*, packet::*};

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
    let mut client = packetz::client::connect("0.0.0.0:5515").await?;
    client.send(b"Hello, Packetz!").await?;
    println!("{}", String::from_utf8(
        client.recv().await?
    )?);
    Ok(())
}

依赖项

这些示例的依赖项

[dependencies]
packetz = "0.1.0" # Replace this with the latest version, if it's not already the latest version.
tokio = { version = "1.29.0", features = ["net", "io-util", "time", "rt", "rt-multi-thread"] }

依赖项

~2–11MB
~119K SLoC