snapview/tokio-tungstenite

What's Proper way to close a connection after split?

Hperigo opened this issue · 1 comments

Hello, I have this code that creates a connection and splits the read and write streams that then are read on the main thread..

What's the proper way to rejoin the two streams and close the connection?

 async fn connect(context: Arc<std::sync::Mutex<WebContext>>) {
        let url = Url::parse("ws://127.0.0.1:3000/").unwrap();
        let (ws_stream, _) = connect_async(url).await.expect("Failed to connect ");

        let (write, mut read) = ws_stream.split();

        let write_join_handle = {
            // Setup sync pipeline for writing messages
            let (write_tx, write_rx) = mpsc::unbounded_channel();
            let write_rx = UnboundedReceiverStream::new(write_rx);
            let join_handle = tokio::spawn(write_rx.map(Ok).forward(write));
            println!("WebSocket handshake has been successfully completed");
            {
                let mut ctx = context.lock().unwrap();
                ctx.tx = Some(write_tx);
                // ctx.read_stream = Some(read);
            }

            join_handle
        };

        let (read_tx, read_rx) = mpsc::unbounded_channel();

        {
            let mut ctx = context.lock().unwrap();
            ctx.rx = Some(read_rx);
        }

        while let Some(result) = read.next().await {
            println!("Got msg");

            match result {
                Ok(msg) => {
                    read_tx.send(msg).unwrap();
                }
                Err(e) => {
                    println!("error receiving message for id {})", e);
                    break;
                }
            };
        }
        println!("Disconnected!");

        write_join_handle.abort();
        context.lock().unwrap().tx = None;