feat: init commit
This commit is contained in:
48
src/main.rs
Normal file
48
src/main.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
#[macro_use] extern crate lazy_static;
|
||||
#[macro_use] extern crate rust_util;
|
||||
|
||||
use std::{env, io::Error};
|
||||
use std::process;
|
||||
use futures_util::StreamExt;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use rust_util::XResult;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Error> {
|
||||
let addr = env::args().nth(1).unwrap_or_else(|| "127.0.0.1:8080".to_string());
|
||||
|
||||
let listener = match TcpListener::bind(&addr).await {
|
||||
Ok(socket) => socket,
|
||||
Err(e) => {
|
||||
failure!("Try listen on: {}, faield: {}", addr, e);
|
||||
process::exit(-1);
|
||||
},
|
||||
};
|
||||
success!("Listening on: {}", addr);
|
||||
|
||||
while let Ok((stream, _)) = listener.accept().await {
|
||||
tokio::spawn(accept_connection(stream));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn accept_connection(stream: TcpStream) {
|
||||
if let Err(e) = inner_accept_connection(stream).await {
|
||||
failure!("Error occurred in accepting connection: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
async fn inner_accept_connection(stream: TcpStream) -> XResult<()> {
|
||||
let addr = stream.peer_addr()?;
|
||||
information!("Peer address: {}", addr);
|
||||
|
||||
let ws_stream = tokio_tungstenite::accept_async(stream).await?;
|
||||
|
||||
information!("New WebSocket connection: {}", addr);
|
||||
|
||||
let (write, read) = ws_stream.split();
|
||||
read.forward(write).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user