-
-
Save dyule/af30554b2257fe2370e39ff739e990b9 to your computer and use it in GitHub Desktop.
Demonstrates a threading bug in ws-rs.
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
/// A thread-based client + server example. It also demonstrates using a struct as a WebSocket | |
/// handler to implement more handler methods than a closure handler allows. | |
extern crate ws; | |
extern crate env_logger; | |
use std::thread; | |
use std::thread::sleep; | |
use std::time::Duration; | |
use ws::{connect, listen, CloseCode, Sender, Handler, Message, Result, Handshake}; | |
fn main () { | |
// Setup logging | |
env_logger::init().unwrap(); | |
// Server WebSocket handler | |
struct Server { | |
out: Sender, | |
} | |
impl Handler for Server { | |
fn on_open(&mut self, _handshake: Handshake) -> Result<()> { | |
sleep(Duration::from_millis(200)); | |
Ok(()) | |
} | |
fn on_message(&mut self, msg: Message) -> Result<()> { | |
println!("Server got message '{}'. ", msg); | |
self.out.send(msg) | |
} | |
fn on_close(&mut self, code: CloseCode, reason: &str) { | |
println!("WebSocket closing for ({:?}) {}", code, reason); | |
println!("Shutting down server after first connection closes."); | |
self.out.shutdown().unwrap(); | |
} | |
} | |
// Server thread | |
let server = thread::spawn(move || { | |
listen("127.0.0.1:3012", |out| { | |
Server { out: out } | |
}).unwrap() | |
}); | |
// Give the server a little time to get going | |
sleep(Duration::from_millis(10)); | |
// Client thread | |
let client = thread::spawn(move || { | |
connect("ws://127.0.0.1:3012", |out| { | |
out.send("Hello WebSocket").unwrap(); | |
move |msg| { | |
println!("Client got message '{}'. ", msg); | |
out.close(CloseCode::Normal) | |
} | |
}).unwrap() | |
}); | |
let _ = server.join(); | |
let _ = client.join(); | |
println!("All done.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment