Separate server and connection handling functions

This commit is contained in:
Greg Heartsfield 2021-11-21 13:48:31 -06:00
parent ee27d0c597
commit dbb535eaaa

View File

@ -4,6 +4,7 @@ use futures_util::StreamExt;
use log::info; use log::info;
use tokio::net::{TcpListener, TcpStream}; use tokio::net::{TcpListener, TcpStream};
use tokio::runtime::Builder; use tokio::runtime::Builder;
use tokio_tungstenite::WebSocketStream;
//use tungstenite::protocol::Message; //use tungstenite::protocol::Message;
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
@ -30,29 +31,22 @@ fn main() -> Result<(), Error> {
let listener = TcpListener::bind(&addr).await.expect("Failed to bind"); let listener = TcpListener::bind(&addr).await.expect("Failed to bind");
info!("Listening on: {}", addr); info!("Listening on: {}", addr);
while let Ok((stream, _)) = listener.accept().await { while let Ok((stream, _)) = listener.accept().await {
tokio::spawn(accept_connection(stream)); tokio::spawn(nostr_server(stream));
} }
}); });
Ok(()) Ok(())
} }
async fn accept_connection(stream: TcpStream) { async fn nostr_server(stream: TcpStream) {
let addr = stream let addr = stream
.peer_addr() .peer_addr()
.expect("connected streams should have a peer address"); .expect("connected streams should have a peer address");
info!("Peer address: {}", addr); info!("Peer address: {}", addr);
let conn = tokio_tungstenite::accept_async(stream).await;
let ws_stream_res = tokio_tungstenite::accept_async(stream).await; match conn {
match ws_stream_res {
Ok(ws_stream) => { Ok(ws_stream) => {
info!("New WebSocket connection: {}", addr); info!("New WebSocket connection: {}", addr);
let (_write, mut read) = ws_stream.split(); process_client(ws_stream).await;
// TODO: error on binary messages
// TODO: error on text messages > MAX_EVENT_SIZE
while let Some(mes_res) = read.next().await {
println!("got {:?}", mes_res);
}
} }
Err(_) => { Err(_) => {
println!("Error"); println!("Error");
@ -60,3 +54,11 @@ async fn accept_connection(stream: TcpStream) {
} }
}; };
} }
async fn process_client(stream: WebSocketStream<TcpStream>) {
let (_write, mut read) = stream.split();
// TODO: error on binary messages
// TODO: error on text messages > MAX_EVENT_SIZE
while let Some(mes_res) = read.next().await {
println!("got {:?}", mes_res);
}
}