Hi,
I was trying an example with running actix web server and toy server (for rpc). Somehow on ctrl+c HTTP server is being stopped but not other tokio tasks.
What I am doing wrong here ?
Cargo.toml
[package]
name = "actix-example"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4"
tokio = { version = "1", features = ["full"] }
[dependencies.toy-rpc]
version = "0.8.6"
features = ["ws_tokio", "tokio_runtime", "server", "client"]
main.rs
use std::sync::Arc;
use std::time::Duration;
use actix_web::{App, HttpServer, Responder, web};
use tokio::net::TcpListener;
use tokio::task;
use toy_rpc::Server;
use crate::rpc::Echo;
#[tokio::main]
async fn main() -> std::io::Result<()> {
// rpc server
let addr = "127.0.0.1:23333";
let echo_service = Arc::new(Echo {});
let server = Server::builder().register(echo_service).build();
let listener = TcpListener::bind(addr).await.unwrap();
let handle = task::spawn(async move {
println!("Starting rpc server at {}", &addr);
server.accept(listener).await.unwrap();
println!("stopping rpc server");
});
// counter handle
let counter_handle = tokio::task::spawn(async {
let mut i = 1;
loop {
tokio::time::sleep(Duration::from_millis(1000)).await;
println!("counter {:?}", i);
i += 1;
}
});
let server = HttpServer::new(move || {
App::new()
.route("/hey", web::get().to(index))
})
.bind("127.0.0.1:8080").unwrap()
.run()
;
server.await.expect("error http server");
println!("stopped http server");
// This is not being called
counter_handle.await?;
println!("stopped counter ");
// This is not being called
handle.await.expect("Error running the RPC server");
println!("stopped rpc server");
Ok(())
}
async fn index() -> impl Responder {
"Hello world!"
}
pub mod rpc {
use toy_rpc::macros::export_impl;
pub struct Echo {}
#[export_impl]
impl Echo {
#[export_method]
pub async fn echo_i32(&self, arg: i32) -> Result<i32, String> {
Ok(arg)
}
}
}
Output after ctrl+c
Starting rpc server at 127.0.0.1:23333
counter 1
counter 2
counter 3
counter 4
counter 5
stopped http server ==>ctrl+c here
counter 6
counter 7