use std::net::{TcpListener, TcpStream}; use std::thread::spawn; use env_logger::Builder; use log::{LevelFilter, error, info}; use tungstenite::extensions::deflate::{DeflateExt, DeflateConfigBuilder}; use tungstenite::handshake::HandshakeRole; use tungstenite::protocol::WebSocketConfig; use tungstenite::server::accept_with_config; use tungstenite::{Error, HandshakeError, Message, Result}; fn must_not_block(err: HandshakeError) -> Error { match err { HandshakeError::Interrupted(_) => panic!("Bug: blocking socket would block"), HandshakeError::Failure(f) => f, } } fn handle_client(stream: TcpStream) -> Result<()> { let deflate_config = DeflateConfigBuilder::default() .max_message_size(None) .build(); let mut socket = accept_with_config( stream, Some(WebSocketConfig { max_send_queue: None, max_frame_size: Some(16 << 20), encoder: DeflateExt::new(deflate_config), }), ) .map_err(must_not_block)?; info!("Running test"); loop { match socket.read_message()? { msg @ Message::Text(_) | msg @ Message::Binary(_) => { socket.write_message(msg)?; } Message::Ping(_) | Message::Pong(_) | Message::Close(_) => {} } } } fn main() { let mut builder = Builder::new(); builder.filter_level(LevelFilter::Trace); builder.init(); let server = TcpListener::bind("127.0.0.1:9002").unwrap(); for stream in server.incoming() { 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), }); } }