forked from 409/chat-app
init
This commit is contained in:
42
src/websockets.rs
Normal file
42
src/websockets.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::{
|
||||
extract::{
|
||||
WebSocketUpgrade,
|
||||
ws::{Message, WebSocket},
|
||||
},
|
||||
response::Response,
|
||||
};
|
||||
|
||||
use futures_util::{
|
||||
SinkExt as _, StreamExt,
|
||||
stream::{SplitSink, SplitStream},
|
||||
};
|
||||
|
||||
pub async fn websocket_handler(upgrade: WebSocketUpgrade) -> Response {
|
||||
upgrade.on_upgrade(handler)
|
||||
}
|
||||
|
||||
async fn handler(socket: WebSocket) {
|
||||
let (sender, receiver) = socket.split();
|
||||
|
||||
tokio::spawn(receive(receiver));
|
||||
tokio::spawn(send(sender));
|
||||
}
|
||||
|
||||
async fn send(mut sender: SplitSink<WebSocket, Message>) {
|
||||
loop {
|
||||
let _ = sender.send("Hello client!".into());
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn receive(mut stream: SplitStream<WebSocket>) {
|
||||
while let Some(Ok(message)) = stream.next().await {
|
||||
let Ok(text) = message.to_text() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
println!("Message: {text}");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user