housleyjk / ws-rs

Lightweight, event-driven WebSockets for Rust.
MIT License
1.46k stars 219 forks source link

Messages sent just before shutdown never go out #332

Open mverleg opened 3 years ago

mverleg commented 3 years ago

I adapted the example in external_shutdown to echo messages.

Example:

extern crate ws;

use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = channel();

    let socket = ws::Builder::new()
        .build(move |out: ws::Sender| {
            // When we get a connection, send a handle to the parent thread
            tx.send(out).unwrap();

            // Dummy message handler
            move |_| {
                println!("Message handler called.");
                Ok(())
            }
        })
        .unwrap();

    let handle = socket.broadcaster();

    let t = thread::spawn(move || {
        socket.listen("127.0.0.1:3012").unwrap();
    });

    let c = thread::spawn(move || ws::connect("ws://127.0.0.1:3012", |out| {
        move |msg| {
            println!("Client got message: '{}'.", msg);
            Ok(())
        }
    }).unwrap());

    let to_client = rx.recv().unwrap();
    to_client.send("welcome").unwrap();

    // Wait for 5 seconds only for incoming connections;
    thread::sleep(Duration::from_millis(1000));

    to_client.send("going down").unwrap();

    // shutdown the server from the outside
    handle.shutdown().unwrap();
    println!("Shutting down server because no connections were established.");

    // Let the server finish up (whether it's waiting for new connections or going down)
    t.join().unwrap();
    c.join().unwrap();
}

How to get all the messages to go out before the server shuts down?

I looked a bit at the code, but both send and shutdown seem to work through Command, so it's not quickly apparent to me what is wrong.