How do I shutdown warp websocket server gracefully

Hi,

newbie coder here. So, I have below code where I spin up a webSocketServer, and for my basic program a client can connect and is working fine. However, I am binding to all address:port, which I want to release when I terminate the program with ctrl+c. I can listen to ctrl+c with ctrlc crate, however, I am not able to find example how to shutdown the server and release all the resources held by the socket server.

I would appreciate if someone could point me to the right direction. thanks!

        pub async fn wsc(&mut self) {
            let clients = self.clients.clone().unwrap();
            let clients = warp::any().map(move || clients.clone());
            let client_id = CLIENT_ID.fetch_add(1, Ordering::Relaxed);
            self.client_id = Some(client_id);

            let routes = warp::path("ws").and(warp::ws()).and(clients).map(
                move |ws: warp::ws::Ws,
                      clients: Arc<RwLock<HashMap<usize, mpsc::UnboundedSender<Message>>>>| {
                    ws.on_upgrade( move |socket| {
                        WebSocketServer::on_client_connect(client_id, socket, clients)
                    })
                },
            );
            warp::serve(routes).run(([0, 0, 0, 0], 4000)).await;
        }

I think warp::Server::bind_with_graceful_shutdown is what you are looking for instead of warp::Server::run, which runs the warp server forever.

1 Like

hi @jofas thank you! that worked.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.