I'm using Axum and trying to establish a websocket connection
pub async fn ws_handler(
ws: WebSocketUpgrade,
) -> impl IntoResponse {
ws.on_upgrade(move |socket| handle_socket(socket))
}
pub async fn handle_socket(mut socket: WebSocket) {
while let Some(msg) = socket.recv().await {
let msg = if let Ok(msg) = msg {
msg
} else {
return;
};
if socket.send(msg).await.is_err() {
return;
}
}
}
async fn main() {
dotenv().ok();
let http_host = env::var("HTTP_HOST").unwrap();
let routes = routes::create_routes();
let http_addr =
SocketAddr::from_str(&http_host).unwrap();
println!("Listening on http://{}", http_addr);
axum::Server::bind(&http_addr)
.serve(routes.into_make_service())
.await
.unwrap();
}
This is my code that is attached to a GET route. From my understanding I should hit this endpoint from my frontend in order for the connection to establish, but can't seem to get it working.
Is there a better way to create a websocket server in Axum? Perhaps a separate websocket server and a seperate http server