tungstenite-rs/examples/autobahn-server.rs

48 lines
1.4 KiB
Rust
Raw Permalink Normal View History

use std::{
net::{TcpListener, TcpStream},
thread::spawn,
};
2017-01-31 18:22:28 +00:00
2019-08-26 17:00:41 +00:00
use log::*;
use tungstenite::{accept, handshake::HandshakeRole, Error, HandshakeError, Message, Result};
fn must_not_block<Role: HandshakeRole>(err: HandshakeError<Role>) -> Error {
match err {
HandshakeError::Interrupted(_) => panic!("Bug: blocking socket would block"),
HandshakeError::Failure(f) => f,
}
}
2017-01-31 18:22:28 +00:00
fn handle_client(stream: TcpStream) -> Result<()> {
let mut socket = accept(stream).map_err(must_not_block)?;
info!("Running test");
2017-01-31 18:22:28 +00:00
loop {
match socket.read()? {
2019-08-26 17:00:41 +00:00
msg @ Message::Text(_) | msg @ Message::Binary(_) => {
socket.send(msg)?;
}
2021-11-02 14:05:03 +00:00
Message::Ping(_) | Message::Pong(_) | Message::Close(_) | Message::Frame(_) => {}
}
2017-01-31 18:22:28 +00:00
}
}
fn main() {
env_logger::init();
2017-01-31 18:22:28 +00:00
let server = TcpListener::bind("127.0.0.1:9002").unwrap();
2017-01-31 18:22:28 +00:00
for stream in server.incoming() {
2019-08-26 17:00:41 +00:00
spawn(move || match stream {
Ok(stream) => {
if let Err(err) = handle_client(stream) {
match err {
Error::ConnectionClosed | Error::Protocol(_) | Error::Utf8 => (),
e => error!("test: {}", e),
}
}
}
Err(e) => error!("Error accepting stream: {}", e),
2017-01-31 18:22:28 +00:00
});
}
}