Last active
March 20, 2021 08:05
-
-
Save tqwewe/718f3e9b52f5a3fa0ce4a129121131c6 to your computer and use it in GitHub Desktop.
Actix channel issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "test" | |
version = "0.1.0" | |
edition = "2018" | |
[dependencies] | |
actix-web = "4.0.0-beta.4" | |
tokio = { version = "1", features = ["full"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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