basic server
This commit is contained in:
parent
3e4f2afc82
commit
59cff14584
3 changed files with 364 additions and 1 deletions
45
src/main.rs
45
src/main.rs
|
@ -1,3 +1,46 @@
|
|||
use std::{net::TcpListener, thread::spawn};
|
||||
|
||||
use tungstenite::{accept, protocol::{frame::coding::CloseCode, CloseFrame}, Message};
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
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");
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue