|
| 1 | +extern crate websocket; |
| 2 | +extern crate futures; |
| 3 | +extern crate tokio_core; |
| 4 | + |
| 5 | +use websocket::message::{Message, OwnedMessage}; |
| 6 | +use websocket::server::InvalidConnection; |
| 7 | +use websocket::async::Server; |
| 8 | +use websocket::async::client::Client; |
| 9 | +use websocket::async::WebSocketFuture; |
| 10 | + |
| 11 | +use tokio_core::reactor::Core; |
| 12 | +use tokio_core::net::TcpStream; |
| 13 | +use futures::{Future, Sink, Stream}; |
| 14 | + |
| 15 | +fn main() { |
| 16 | + let mut core = Core::new().unwrap(); |
| 17 | + let handle = core.handle(); |
| 18 | + // bind to the server |
| 19 | + let server = Server::bind("127.0.0.1:2794", &handle).unwrap(); |
| 20 | + |
| 21 | + // time to build the server's future |
| 22 | + // this will be a struct containing everything the server is going to do |
| 23 | + |
| 24 | + // a stream of incoming connections |
| 25 | + let f = server.incoming() |
| 26 | + // we don't wanna save the stream if it drops |
| 27 | + .map_err(|InvalidConnection { error, .. }| error.into()) |
| 28 | + // negotiate with the client |
| 29 | + .and_then(|upgrade| { |
| 30 | + // check if it has the protocol we want |
| 31 | + let uses_proto = upgrade.protocols().iter().any(|s| s == "rust-websocket"); |
| 32 | + |
| 33 | + let f: WebSocketFuture<Option<Client<TcpStream>>> = if uses_proto { |
| 34 | + // accept the request to be a ws connection if it does |
| 35 | + Box::new(upgrade.use_protocol("rust-websocket").accept().map(|(s, _)| Some(s))) |
| 36 | + } else { |
| 37 | + // reject it if it doesn't |
| 38 | + Box::new(upgrade.reject().map(|_| None).map_err(|e| e.into())) |
| 39 | + }; |
| 40 | + f |
| 41 | + }) |
| 42 | + // get rid of the bad connections |
| 43 | + .filter_map(|i| i) |
| 44 | + // send a greeting! |
| 45 | + .and_then(|s| s.send(Message::text("Hello World!").into())) |
| 46 | + // simple echo server impl |
| 47 | + .and_then(|s| { |
| 48 | + let (sink, stream) = s.split(); |
| 49 | + stream.filter_map(|m| { |
| 50 | + println!("Message from Client: {:?}", m); |
| 51 | + match m { |
| 52 | + OwnedMessage::Ping(p) => Some(OwnedMessage::Pong(p)), |
| 53 | + OwnedMessage::Pong(_) => None, |
| 54 | + _ => Some(m), |
| 55 | + } |
| 56 | + }).forward(sink) |
| 57 | + }) |
| 58 | + // TODO: ?? |
| 59 | + .collect(); |
| 60 | + |
| 61 | + core.run(f).unwrap(); |
| 62 | +} |
0 commit comments