Skip to content

Instantly share code, notes, and snippets.

@thepeak99
Created June 10, 2022 21:17
Show Gist options
  • Save thepeak99/204148f9945a0fffa979ac42929822f7 to your computer and use it in GitHub Desktop.
Save thepeak99/204148f9945a0fffa979ac42929822f7 to your computer and use it in GitHub Desktop.
Long polling demo with Rust and Actix
[package]
name = "long-poll-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4"
tokio = { version = "1.19", features = ["sync"] }
serde = { version = "1", features = ["derive"] }
use std::collections::HashMap;
use actix_web::{web, App, HttpServer, Responder};
use serde::Deserialize;
use tokio::sync::mpsc::{unbounded_channel, UnboundedSender};
use tokio::sync::Mutex;
struct State {
channels: Mutex<HashMap<String, UnboundedSender<String>>>,
}
#[derive(Deserialize)]
struct ReceiverInfo {
id: String,
}
#[derive(Deserialize)]
struct SenderInfo {
id: String,
text: String,
}
async fn receive(data: web::Data<State>, info: web::Query<ReceiverInfo>) -> impl Responder {
let (tx, mut rx) = unbounded_channel();
data.channels.lock().await.insert(info.id.clone(), tx);
rx.recv().await
}
async fn send(data: web::Data<State>, info: web::Query<SenderInfo>) -> impl Responder {
let tx = data.channels.lock().await.get(&info.id).unwrap().clone();
tx.send(info.text.clone()).unwrap();
"Ok"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let state = web::Data::new(State {
channels: Mutex::new(HashMap::new()),
});
HttpServer::new(move || {
App::new()
.app_data(state.clone())
.route("/receive", web::get().to(receive))
.route("/send", web::get().to(send))
})
.bind(("0.0.0.0", 8080))?
.run()
.await
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment