|
| 1 | +extern crate websocket; |
| 2 | +extern crate futures; |
| 3 | +extern crate tokio_core; |
| 4 | + |
| 5 | +use websocket::message::OwnedMessage; |
| 6 | +use websocket::server::InvalidConnection; |
| 7 | +use websocket::async::Server; |
| 8 | + |
| 9 | +use tokio_core::reactor::Core; |
| 10 | +use futures::{Future, Sink, Stream}; |
| 11 | + |
| 12 | +fn main() { |
| 13 | + let mut core = Core::new().unwrap(); |
| 14 | + let handle = core.handle(); |
| 15 | + // bind to the server |
| 16 | + let server = Server::bind("127.0.0.1:9002", &handle).unwrap(); |
| 17 | + |
| 18 | + // time to build the server's future |
| 19 | + // this will be a struct containing everything the server is going to do |
| 20 | + |
| 21 | + // a stream of incoming connections |
| 22 | + let f = server.incoming() |
| 23 | + // we don't wanna save the stream if it drops |
| 24 | + .map_err(|InvalidConnection { error, .. }| error) |
| 25 | + .for_each(|(upgrade, addr)| { |
| 26 | + // accept the request to be a ws connection |
| 27 | + println!("Got a connection from: {}", addr); |
| 28 | + let f = upgrade |
| 29 | + .accept() |
| 30 | + .and_then(|(s, _)| { |
| 31 | + // simple echo server impl |
| 32 | + let (sink, stream) = s.split(); |
| 33 | + stream |
| 34 | + .take_while(|m| Ok(!m.is_close())) |
| 35 | + .filter_map(|m| { |
| 36 | + match m { |
| 37 | + OwnedMessage::Ping(p) => Some(OwnedMessage::Pong(p)), |
| 38 | + OwnedMessage::Pong(_) => None, |
| 39 | + _ => Some(m), |
| 40 | + } |
| 41 | + }) |
| 42 | + .forward(sink) |
| 43 | + .and_then(|(_, sink)| { |
| 44 | + sink.send(OwnedMessage::Close(None)) |
| 45 | + }) |
| 46 | + }); |
| 47 | + |
| 48 | + handle.spawn(f.map_err(move |e| println!("{}: '{:?}'", addr, e)) |
| 49 | + .map(move |_| println!("{} closed.", addr))); |
| 50 | + Ok(()) |
| 51 | + }); |
| 52 | + |
| 53 | + core.run(f).unwrap(); |
| 54 | +} |
| 55 | + |
0 commit comments