~starkingdoms/starkingdoms

e259a6768336a693a62c88b894ff777a6e4fd55a — c0repwn3r 2 years ago 7128e45
fix the client ping system
3 files changed, 33 insertions(+), 13 deletions(-)

M client/src/lib.rs
M server/src/handler.rs
M web/play.html
M client/src/lib.rs => client/src/lib.rs +16 -8
@@ 182,7 182,23 @@ pub async fn main(gateway: &str, username: &str, backoff: i32, textures: Texture
}

#[wasm_bindgen]
pub async fn send_ping_pong() -> Result<(), JsError> {
    let mut client = CLIENT.write()?;

    if client.client_data.is_none() {
        return Err(JsError::new("Client not yet initialized"));
    }

    let client_data = client.client_data.as_mut().unwrap();

    send!(client_data.tx, &MessageC2S::Ping {}).await?;

    Ok(())
}

#[wasm_bindgen]
pub async fn update_socket() -> Result<(), JsError> {

    let mut client = CLIENT.write()?;

    if client.client_data.is_none() {


@@ 201,11 217,6 @@ pub async fn update_socket() -> Result<(), JsError> {
        return Err(JsError::new("Connection timed out"));
    }

    if client_data.pong_timeout - 3 < (js_sys::Date::now() as u64 / 1000) {
        // send ping
        send!(client_data.tx, &MessageC2S::Ping {}).await?;
    }

    let maybe_msg: Option<MessageS2C> = match recv!(client_data.rx) {
        Ok(r) => r,
        Err(e) => {


@@ 236,17 247,14 @@ pub async fn update_socket() -> Result<(), JsError> {
                chatbox.append_child(&new_elem).unwrap();
            },
            MessageS2C::Pong {} => {
                info!("this is a pong response");
                client_data.pong_timeout = (js_sys::Date::now() as u64 / 1000) + PONG_MAX_TIMEOUT
            },
            MessageS2C::PlanetData { planets } => {
                debug!("updated planet information {:?}", planets);
                client.planets = planets;
            },
            MessageS2C::Position { x, y } => {
                client.x = x;
                client.y = y;
                debug!("updated position information {}, {}", x, y);
            }
            _ => {
                warn!("server sent unexpected packet {:?}, ignoring", msg);

M server/src/handler.rs => server/src/handler.rs +4 -4
@@ 20,10 20,10 @@ use crate::{send, recv, SCALE};
pub async fn handle_client(mgr: ClientManager, data: Arc<RwLock<PhysicsData>>, remote_addr: SocketAddr, mut rx: Receiver<ClientHandlerMessage>, mut client_tx: SplitSink<WebSocketStream<Upgraded>, Message>, mut client_rx: SplitStream<WebSocketStream<Upgraded>>) -> Result<(), Box<dyn Error>> {
    let mut state = State::Handshake;
    let mut username = String::new();
    let mut ping_timeout = SystemTime::now() + Duration::from_secs(5);
    let mut ping_timeout = SystemTime::now() + Duration::from_secs(10);

    loop {
        info!("{}", ping_timeout.duration_since(UNIX_EPOCH).unwrap().as_secs() - SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs());

        if let Some(msg) = rx.recv().await {
            match msg {
                ClientHandlerMessage::Tick => {} // this intentionally does nothing,


@@ 51,7 51,7 @@ pub async fn handle_client(mgr: ClientManager, data: Arc<RwLock<PhysicsData>>, r
        }

        if ping_timeout < SystemTime::now() {
            warn!("[{}] ping timeout", remote_addr);
            error!("[{}] ping timeout", remote_addr);
            send!(client_tx, &MessageS2C::Goodbye {
                reason: PingPongTimeout
            }).await?;


@@ 168,7 168,7 @@ pub async fn handle_client(mgr: ClientManager, data: Arc<RwLock<PhysicsData>>, r
                        },
                        MessageC2S::Ping {} => {
                            send!(client_tx, &MessageS2C::Pong {}).await?;
                            ping_timeout = SystemTime::now() + Duration::from_secs(5);
                            ping_timeout = SystemTime::now() + Duration::from_secs(10);
                        }
                    }
                }

M web/play.html => web/play.html +13 -1
@@ 25,7 25,7 @@
        <script type="module">
            // If you're getting build errors here | you need to run `just build_client_bundle` first, to compile client code
            //                                     v
            import init, { rust_init, send_chat, update_socket, set_status, get_texture, render_frame } from "./dist/starkingdoms_client.js";
            import init, { rust_init, send_chat, update_socket, set_status, get_texture, render_frame, send_ping_pong } from "./dist/starkingdoms_client.js";
            init().then(() => {
                const urlSearchParams = new URLSearchParams(window.location.search);



@@ 39,9 39,21 @@
                    });

                    let interval_id;
                    let interval_id2;

                    interval_id = setInterval(() => {
                        update_socket().catch((e) => {
                            clearInterval(interval_id);
                            clearInterval(interval_id2);
                            set_status("There was an error. Reload the page to reconnect.")
                            throw e;
                        });
                    }, 5);

                    interval_id2 = setInterval(() => {
                        send_ping_pong().catch((e) => {
                            clearInterval(interval_id2);
                            clearInterval(interval_id);
                            set_status("There was an error. Reload the page to reconnect.")
                            throw e;
                        });