Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't establish websocket connection between browser and server when using dx serve #3894

Open
1 task done
arvidfm opened this issue Mar 20, 2025 · 0 comments · May be fixed by #3895
Open
1 task done

Can't establish websocket connection between browser and server when using dx serve #3894

arvidfm opened this issue Mar 20, 2025 · 0 comments · May be fixed by #3895
Labels
bug Something isn't working cli Related to the dioxus-cli program

Comments

@arvidfm
Copy link

arvidfm commented Mar 20, 2025

Problem

When using dx serve with a custom Axum websocket endpoint (using WebSocketUpgrade), websocket connections between the browser and the server fail, even though the same code works when using dx bundle.

Also see #2155 which was previously closed, but this is still an issue for browser-to-server connections.

Steps To Reproduce

Steps to reproduce the behavior:

Cargo.toml
[dependencies]
dioxus = { version = "0.6.3", features = ["fullstack"] }
dioxus-cli-config = "0.6.3"
futures = "0.3.31"
tokio = { version = "1.43.0", optional = true }
axum = { version = "0.7.9", optional = true }
gloo = { version = "0.11.0", optional = true, features = ["net"] }

[features]
default = []
web = ["dioxus/web", "dep:gloo"]
server = ["dioxus/server", "dep:tokio", "dep:axum"]
main.rs
use dioxus::prelude::*;

fn main() {
    #[cfg(not(feature = "server"))]
    dioxus::launch(App);
    #[cfg(feature = "server")]
    server::server_main();
}

#[cfg(feature = "server")]
mod server {
    use axum::extract::WebSocketUpgrade;
    use axum::response::IntoResponse;
    use dioxus::logger::tracing::{info, warn};
    use dioxus::prelude::*;
    use futures::StreamExt;

    #[tokio::main]
    pub async fn server_main() {
        dioxus::logger::initialize_default();
        let socket_addr = dioxus_cli_config::fullstack_address_or_localhost();
        let router = axum::Router::new()
            .serve_dioxus_application(ServeConfigBuilder::new(), super::App)
            .route("/events", axum::routing::any(websocket_handler))
            .into_make_service();

        let listener = tokio::net::TcpListener::bind(socket_addr).await.unwrap();
        axum::serve(listener, router).await.unwrap();
    }

    async fn websocket_handler(ws: WebSocketUpgrade) -> impl IntoResponse {
        ws.on_upgrade(|mut ws| async move {
            while let Some(msg) = ws.next().await {
                match msg {
                    Ok(msg) => info!("Got message: {msg:?}"),
                    Err(e) => warn!("Error receiving message: {e}"),
                }
            }
        })
    }
}

#[component]
fn App() -> Element {
    #[cfg(feature = "web")]
    {
        _ = use_future(|| async {
            use dioxus::logger::tracing::error;
            use futures::SinkExt;
            use gloo::net::websocket::futures::WebSocket;

            let mut ws = match WebSocket::open("/events") {
                Ok(ws) => ws,
                Err(e) => {
                    error!("Could not open websocket connection: {e}");
                    return;
                }
            };

            if let Err(e) = ws
                .send(gloo::net::websocket::Message::Text(
                    "this is a websocket message".into(),
                ))
                .await
            {
                error!("Could not send websocket message: {e}");
            }
        });
    }

    rsx! {
        "hi"
    }
}
  1. Create a new Dioxus project with the above files
  2. Run dx bundle --platform web && target/dx/$PROJECT_NAME/release/web/server
  3. Navigate to http://127.0.0.1:8080/
  4. Run dx serve
  5. Navigate to http://127.0.0.1:8080/

Expected behavior

The websocket message is successfully received by the server in both cases.

Actual output

The connection fails to be established when using dx serve:

> dx bundle --platform web
[...]
> target/dx/websocket_test/release/web/server
2025-03-20T23:44:26.893572Z  INFO websocket_test::server: Got message: Text("this is a websocket message")
2025-03-20T23:44:26.893600Z  INFO websocket_test::server: Got message: Close(None)
^C
> dx serve
[...]
23:48:27 [dev] [101] /events
23:48:27 [server]  WARN Error receiving message: WebSocket protocol error: Connection reset without closing handshake

Environment:

  • Dioxus version: 0.6.3, main
  • Rust version: 1.85.1
  • OS info: Arch Linux
  • App platform: fullstack (web + server)

Questionnaire

  • I would like to fix and I have a solution.
@arvidfm arvidfm added the bug Something isn't working label Mar 20, 2025
@ealmloff ealmloff added the cli Related to the dioxus-cli program label Mar 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working cli Related to the dioxus-cli program
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants