36 lines
1.0 KiB
Rust
36 lines
1.0 KiB
Rust
|
use std::env;
|
||
|
use std::net::SocketAddr;
|
||
|
|
||
|
use futures_util::StreamExt;
|
||
|
use tokio::net::{TcpListener, TcpStream};
|
||
|
|
||
|
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||
|
|
||
|
async fn accept_connection(stream: TcpStream, addr: SocketAddr) -> Result<(), BoxError> {
|
||
|
println!("Peer address: {}", addr);
|
||
|
|
||
|
|
||
|
let ws_stream = tokio_tungstenite::accept_async(stream)
|
||
|
.await
|
||
|
.err(format!("Error during WS handshake.").into());
|
||
|
|
||
|
println!("New WebSocket connection: {}", addr);
|
||
|
|
||
|
let (write, read) = ws_stream.split();
|
||
|
read.forward(write).await.expect("Failed to forward message")
|
||
|
}
|
||
|
|
||
|
#[tokio::main]
|
||
|
async fn main() -> Result<(), BoxError> {
|
||
|
// Create the event loop and TCP listener we'll accept connections on.
|
||
|
let addr = env::args().nth(1).unwrap_or_else(|| "127.0.0.1:8080".to_string());
|
||
|
let try_socket = TcpListener::bind(&addr).await;
|
||
|
let mut listener = try_socket.expect("Failed to bind");
|
||
|
|
||
|
while let Ok((stream, addr)) = listener.accept().await {
|
||
|
tokio::spawn(accept_connection(stream, addr));
|
||
|
}
|
||
|
|
||
|
Ok(())
|
||
|
}
|