2025-04-08 17:48:38 +05:00
|
|
|
use std::{net::TcpListener, thread::spawn};
|
|
|
|
|
|
|
|
use tungstenite::{accept, protocol::{frame::coding::CloseCode, CloseFrame}, Message};
|
|
|
|
|
2025-04-07 17:31:16 +05:00
|
|
|
fn main() {
|
2025-04-08 17:48:38 +05:00
|
|
|
let server = TcpListener::bind("0.0.0.0:9001").unwrap();
|
|
|
|
for stream in server.incoming() {
|
|
|
|
spawn(move || {
|
|
|
|
let mut websocket = accept(stream.unwrap()).unwrap();
|
|
|
|
println!("Connection Received");
|
|
|
|
loop {
|
|
|
|
let res = websocket.read();
|
|
|
|
|
|
|
|
match res {
|
|
|
|
Ok(Message::Text(txtmsg)) => {
|
|
|
|
println!("received: {}", txtmsg);
|
|
|
|
let strmsg = format!("i shall send this back to you {}", txtmsg.to_string());
|
|
|
|
websocket.send(Message::text(strmsg)).unwrap();
|
|
|
|
|
|
|
|
}
|
|
|
|
Ok(Message::Close(_)) => {
|
|
|
|
match websocket.send(Message::Close(Some(CloseFrame{
|
|
|
|
code: CloseCode::Normal,
|
|
|
|
reason: "Connection Closed :)".into()
|
|
|
|
}))) {
|
|
|
|
Ok(_) => println!("Close frame sent succesfully"),
|
|
|
|
Err(e) => println!("Failed to send close frame (connection may already be closed): {}", e)
|
|
|
|
};
|
|
|
|
println!("closing connection");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
println!("MyError Occured: {}", e);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
println!("not handled");
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
});
|
|
|
|
}
|
2025-04-07 17:31:16 +05:00
|
|
|
}
|