1 use std::{net::TcpListener, thread::spawn};
2 use tungstenite::{
3     accept_hdr_with_config,
4     handshake::server::{Request, Response},
5     protocol::WebSocketConfig,
6 };
7 
main()8 fn main() {
9     env_logger::init();
10     let server = TcpListener::bind("127.0.0.1:3012").unwrap();
11     for stream in server.incoming() {
12         spawn(move || {
13             let callback = |req: &Request, mut response: Response| {
14                 println!("Received a new ws handshake");
15                 println!("The request's path is: {}", req.uri().path());
16                 println!("The request's headers are:");
17                 for (ref header, _value) in req.headers() {
18                     println!("* {}", header);
19                 }
20 
21                 // Let's add an additional header to our response to the client.
22                 let headers = response.headers_mut();
23                 headers.append("MyCustomHeader", ":)".parse().unwrap());
24                 headers.append("SOME_TUNGSTENITE_HEADER", "header_value".parse().unwrap());
25 
26                 Ok(response)
27             };
28 
29             let config = Some(WebSocketConfig {
30                 // This setting allows to accept client frames which are not masked
31                 // This is not in compliance with RFC 6455 but might be handy in some
32                 // rare cases where it is necessary to integrate with existing/legacy
33                 // clients which are sending unmasked frames
34                 accept_unmasked_frames: true,
35                 ..<_>::default()
36             });
37 
38             let mut websocket = accept_hdr_with_config(stream.unwrap(), callback, config).unwrap();
39 
40             loop {
41                 let msg = websocket.read().unwrap();
42                 if msg.is_binary() || msg.is_text() {
43                     println!("received message {}", msg);
44                 }
45             }
46         });
47     }
48 }
49