RakNet icon indicating copy to clipboard operation
RakNet copied to clipboard

[QUESTION] Can I use this lib with bincode serialize/deserialize?

Open honnisha opened this issue 1 year ago • 0 comments

Issue / Question: I want to create network for non mc game and use bincode for serialize/deserialize messages.

Client receiving messages, that I don't send, like:

- received [16, 4, 192, 168, 0, 185, 153, 67, 0, 0, 4, 255, 255, 255, 255, 74, 188, 4, 255, 255, 255, 255, 74, 189, 4, 255, 255, 255, 255, 74, 190, 4, 255, 255, 255, 255, 74, 191, 4, 255, 255, 255, 255, 74, 192, 0, 0, 0, 0, 103, 50, 37, 198, 0, 0, 0, 0, 103, 50, 37, 198]
- received [0, 0, 0, 0, 0, 103, 50, 37, 205]

Can I filter these built-in messages?

The code that I use for the test
use clap::Parser;
use rak_rs::client::{Client as RakRsClient, DEFAULT_MTU};
use rak_rs::connection::Connection;
use rak_rs::protocol::reliability::Reliability;
use rak_rs::Listener;
use std::error::Error;

struct Server {
    listener: Listener,
}

impl Server {
    pub async fn create(ip_port: String) -> Self {
        log::info!("Binding {}...", ip_port);
        let listener = Listener::bind(ip_port.clone()).await.unwrap();
        log::info!("Server started; Listening on: {}", ip_port);
        Self { listener }
    }

    pub async fn run(&mut self) {
        self.listener.start().await.unwrap();

        loop {
            let conn = self.listener.accept().await.unwrap();
            tokio::task::spawn(Server::handle(conn));
        }
    }

    pub async fn handle(mut conn: Connection) {
        loop {
            // keeping the connection alive
            if conn.is_closed().await {
                log::info!("Connection {} closed", conn.address.ip());
                break;
            }
            if let Ok(packet) = conn.recv().await {

                match bincode::deserialize::<String>(&packet) {
                    Ok(e) => log::info!("- decoded: {}", e),
                    Err(_) => log::info!("- received {:?} ", packet),
                };
            }
        }
    }
}

struct Client {
    client: RakRsClient,
}

impl Client {
    pub async fn create(ip_port: String) -> Self {
        log::info!("Connecting to {}...", ip_port);
        let mut client = RakRsClient::new(11, DEFAULT_MTU)
            .with_timeout(20)
            .with_handshake_timeout(3);

        for _ in 0..3 {
            if let Err(e) = client.connect(ip_port.clone()).await {
                log::info!("Failed to connect: {}, trying again...", e);
            } else {
                break;
            }
        }
        if !client.is_connected().await {
            panic!("Failed to connect to server after 3 attempts. Exiting...");
        }
        log::info!("Client started; Listening on: {}", ip_port);
        Self { client }
    }

    pub async fn run(&mut self) {
        loop {
            let packet = self.client.recv().await.unwrap();
            match bincode::deserialize::<String>(&packet) {
                Ok(e) => log::info!("- decoded: {}", e),
                Err(_) => log::info!("- received {:?} ", packet),
            };

            let msg = "messAge".to_string();
            let encoded = bincode::serialize(&msg).unwrap();
            self.client.send(&encoded, Reliability::Reliable, 0).await.unwrap();
            log::info!("Sended \"{}\"", msg);
        }
    }
}

/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    #[arg(short, long, default_value_t = String::from("192.168.0.185:25565"))]
    ip: String,

    /// Number of times to greet
    #[arg(short = 't', long, default_value_t = String::from("client"))]
    run_type: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    tracing_subscriber::fmt::init();

    let args = Args::parse();
    log::info!("args: {:?}", args);

    if args.run_type == "server".to_string() {
        let mut server = Server::create(args.ip.clone()).await;
        server.run().await;
    } else {
        let mut client = Client::create(args.ip.clone()).await;
        client.run().await;
    }
    Ok(())
}

honnisha avatar Nov 11 '24 15:11 honnisha