summaryrefslogtreecommitdiffstats
path: root/third_party/rust/ws/examples/threaded.rs
blob: 35cf0002fcc3094f017d1e3d18a4c3bc030d3f03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
extern crate env_logger;
/// 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;

use std::thread;
use std::thread::sleep;
use std::time::Duration;

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

fn main() {
    // Setup logging
    env_logger::init();

    // Server WebSocket handler
    struct Server {
        out: Sender,
    }

    impl Handler for Server {
        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 }).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.")
}