r0xsh
4/11/2017 - 1:54 PM

How a websocket in another thread can use parent's functions

How a websocket in another thread can use parent's functions

extern crate ws;

use std::thread;

use ws::{listen, CloseCode, Sender, Handler, Message, Result};

fn is_odd(n: ws::Message) -> String {
    match n.into_text() {
        Ok(e) => {
            match e.as_ref() {
                "0" => "Non".to_string(),
                "1" => "Oui".to_string(),
                _ => "Heu... Non".to_string(),
            }
        }
        _ => panic!("TA TOUT CASSE"),
    }
}

fn main() {

    struct Server(Sender);

    impl Handler for Server {
        fn on_message(&mut self, msg: Message) -> Result<()> {
            println!("Server got message '{}'. ", msg);
            let ret = is_odd(msg);
            self.0.send(ret)
        }

        fn on_close(&mut self, code: CloseCode, reason: &str) {
            println!("WebSocket closing for ({:?}) {}", code, reason);
            self.0.shutdown().unwrap();
        }
    }

    // Spawn du listenner dans un nouveau thread
    thread::spawn(move || { listen("127.0.0.1:3012", |out| Server(out)).unwrap(); });

    // Boucle infinie pour garder le programme ouvert
    loop {
        thread::sleep(std::time::Duration::from_secs(10))
    }

}