Created
April 11, 2017 13:54
-
-
Save r0xsh/aeb689e876fb054e1b15dedb53a0c1e0 to your computer and use it in GitHub Desktop.
How a websocket in another thread can use parent's functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment