Skip to content

Instantly share code, notes, and snippets.

@jrfk
Last active November 7, 2023 01:58
Show Gist options
  • Save jrfk/26e46e86c441c83c5f952f7f423825fa to your computer and use it in GitHub Desktop.
Save jrfk/26e46e86c441c83c5f952f7f423825fa to your computer and use it in GitHub Desktop.
websocket_by_rust/main.rs
[dependencies]
tokio = { version = "1", features = ["full"] }
warp = "0.3"
tokio-tungstenite = "0.15"
use warp::Filter;
use tokio_tungstenite::tungstenite::protocol::Message;
use tokio::sync::mpsc;
#[tokio::main]
async fn main() {
// WebSocketのエンドポイントを設定
let ws_route = warp::path("echo")
.and(warp::ws())
.map(|ws: warp::ws::Ws| {
ws.on_upgrade(handle_connection)
});
warp::serve(ws_route)
.run(([127, 0, 0, 1], 3030))
.await;
}
async fn handle_connection(ws: warp::ws::WebSocket) {
let (mut user_ws_tx, mut user_ws_rx) = ws.split();
let (tx, mut rx) = mpsc::unbounded_channel();
// メッセージを受信してエコーバックする
while let Some(result) = user_ws_rx.next().await {
match result {
Ok(msg) => {
if msg.is_text() || msg.is_binary() {
tx.send(msg).unwrap();
}
}
Err(_e) => {
eprintln!("Error during the websocket handshake occurred");
return;
}
}
}
// エコーバックメッセージを送信
while let Some(message) = rx.recv().await {
let _ = user_ws_tx.send(message).await;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment