Skip to content

Instantly share code, notes, and snippets.

@tqwewe
Last active March 20, 2021 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tqwewe/718f3e9b52f5a3fa0ce4a129121131c6 to your computer and use it in GitHub Desktop.
Save tqwewe/718f3e9b52f5a3fa0ce4a129121131c6 to your computer and use it in GitHub Desktop.
Actix channel issue
[package]
name = "test"
version = "0.1.0"
edition = "2018"
[dependencies]
actix-web = "4.0.0-beta.4"
tokio = { version = "1", features = ["full"] }
use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use tokio::sync::broadcast::{self, Sender};
async fn send(tx: web::Data<Sender<String>>, data: String) -> Result<HttpResponse, HttpResponse> {
println!("Sender count: {}", tx.receiver_count());
tx.send(data).map_err(|err| {
println!("Could not send to channel. {:?}", err);
HttpResponse::InternalServerError()
})?;
println!("Sent data");
Ok(HttpResponse::Ok().body("ok"))
}
async fn receive(tx: web::Data<Sender<String>>) -> impl Responder {
let mut rx = tx.subscribe();
tokio::spawn(async move {
println!("Spawned listener...");
while let Ok(data) = rx.recv().await {
println!("Received data: {:?}", data);
}
println!("Exited listener...");
});
HttpResponse::Ok().body("ok")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
let (tx, _rx) = broadcast::channel::<String>(10);
App::new()
.data(tx)
.route("/send", web::post().to(send))
.route("/receive", web::get().to(receive))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
// 1. SPAWN RECEIVER
// $ curl http://localhost:8080/receive
// 2. SEND MESSAGE
// $ curl http://localhost:8080/send --data hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment