Skip to content

Commit 20f5ca0

Browse files
authored
Update tcp.rs
1 parent 1215405 commit 20f5ca0

File tree

1 file changed

+40
-8
lines changed

1 file changed

+40
-8
lines changed

examples/transport/src/tcp.rs

Lines changed: 40 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,63 @@
11
use common::calculator::Calculator;
22
use rmcp::{serve_client, serve_server};
3+
use tracing::info;
4+
use tracing_subscriber::EnvFilter;
35

46
mod common;
57
#[tokio::main]
68
async fn main() -> anyhow::Result<()> {
7-
tokio::spawn(server());
9+
tracing_subscriber::fmt()
10+
.with_env_filter(EnvFilter::from_default_env().add_directive("info".parse()?))
11+
.init();
12+
13+
14+
let (tx, rx) = tokio::sync::oneshot::channel();
15+
tokio::spawn(server(tx));
16+
rx.await??;
817
client().await?;
918
Ok(())
1019
}
1120

12-
async fn server() -> anyhow::Result<()> {
13-
let tcp_listener = tokio::net::TcpListener::bind("127.0.0.1:8001").await?;
14-
while let Ok((stream, _)) = tcp_listener.accept().await {
21+
async fn server(ready_tx: tokio::sync::oneshot::Sender<anyhow::Result<()>>) {
22+
23+
let bind_result = tokio::net::TcpListener::bind("127.0.0.1:8001").await;
24+
let listener = match bind_result {
25+
Ok(l) => l,
26+
Err(e) => {
27+
let _ = ready_tx.send(Err(e.into()));
28+
return;
29+
}
30+
};
31+
32+
info!("Server listening on {}", listener.local_addr().unwrap());
33+
let _ = ready_tx.send(Ok(()));
34+
35+
36+
while let Ok((stream, addr)) = listener.accept().await {
37+
info!("Accepted connection from: {}", addr);
38+
1539
tokio::spawn(async move {
16-
let server = serve_server(Calculator, stream).await?;
17-
server.waiting().await?;
18-
anyhow::Ok(())
40+
match serve_server(Calculator, stream).await {
41+
Ok(server) => {
42+
if let Err(e) = server.waiting().await {
43+
info!("Connection closed with error: {}", e);
44+
}
45+
}
46+
Err(e) => {
47+
info!("Failed to serve connection: {}", e);
48+
}
49+
};
1950
});
2051
}
21-
Ok(())
2252
}
2353

2454
async fn client() -> anyhow::Result<()> {
55+
info!("Client connecting to server...");
2556
let stream = tokio::net::TcpSocket::new_v4()?
2657
.connect("127.0.0.1:8001".parse()?)
2758
.await?;
2859
let client = serve_client((), stream).await?;
60+
info!("Client connected successfully");
2961
let tools = client.peer().list_tools(Default::default()).await?;
3062
println!("{:?}", tools);
3163
Ok(())

0 commit comments

Comments
 (0)