Crates.io | websocket-rs |
lib.rs | websocket-rs |
version | 0.1.4 |
source | src |
created_at | 2020-06-08 17:23:03.563538 |
updated_at | 2020-06-17 21:59:04.404913 |
description | Designed for https://github.com/euvoor/hawk |
homepage | https://github.com/euvoor/hawk |
repository | https://github.com/euvoor/hawk/tree/master/daemon/websocket |
max_upload_size | |
id | 251439 |
size | 21,065 |
Designed for HAWK
use tokio::net::TcpListener;
use http_rs::Http;
use websocket_rs::{ Websocket, Opcode };
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Listening for websocket connections on 127.0.0.1:8080");
while let Ok((stream, addr)) = listener.accept().await {
tokio::spawn(async move {
println!("New connection from {:?}", addr);
let mut http = Http::new(stream);
if let Some(req) = http.next().await {
if req.for_websocket() {
let mut ws = Websocket::new_with_key(
http.transport.into_inner(),
req.headers.get("sec-websocket-key").unwrap().to_string()
);
while let Some(msg) = ws.next().await {
println!("{:?}", msg);
if msg.opcode == Opcode::Text {
let response = format!("Received: {:?}", msg.payload);
ws.send_text(response).await.unwrap();
}
}
println!("Client from {:?} disconnected", addr);
}
}
});
}
Ok(())
}