housleyjk / ws-rs

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

Sender sends messages to closed websocket #316

Open ghost opened 4 years ago

ghost commented 4 years ago

I am cloning the Senders and sending them to another thread. Sending messages to the websockets works fine, but once the websocket is closed, calling sender.send("message") still returns Ok(()). How do I change it so that calling send() on the Sender of a dead websocket returns an error? Also, where do the messages go after the websocket is closed? Do they just get discarded?

Here is an isolated example:

use std::thread;
use std::sync::mpsc;
use ws::{listen, Handler, Handshake, CloseCode, Result};

struct Server {
    out: ws::Sender,
    tx: mpsc::Sender<ws::Sender>
}

impl Handler for Server {
    fn on_open(&mut self, _: Handshake) -> Result<()> {
        self.tx.send(self.out.clone()).unwrap();

        Ok(())
    }
}

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

    thread::spawn(move || {
        loop {
            let out: ws::Sender = rx.recv().unwrap();
            out.send("Hello").unwrap();
            out.close(CloseCode::Normal).unwrap();

            //////////
            //MY ISSUE
            //
            //Why doesn't this unwrap() panic, and what happens to the "Hey" message - is it discarded?
            out.send("Hey").unwrap();
        }
    });

    listen("127.0.0.1:3012", |out| {
        Server {
            out: out,
            tx: tx.clone()
        }
    }).unwrap();
}

How do I detect whether or not the websocket connected to the Sender has been closed?