Can't Connect to Tokio Server

Dear Community,
I'm new to Rust but wanted to implement a simple Client-Server using Tokio. I've managed to get it working when using the std::net::{TcpStream,TcpListener} but now I wanted to take up a notch and use Tokio's Tcp. The problem I am having is that I cannot connect my client to the socket where the server is listening.

Server:

async fn process(socket: TcpStream) {
    println!("New client: {:?}", socket.peer_addr().unwrap());
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            // Process each socket concurrently.
            process(socket).await
        });
    }
}

Client:

#[tokio::main]
async fn main() {

    let mut stream: TcpStream = TcpStream::connect("127.0.0.1:8080").await.unwrap();
    println!("Hello, world!");
}

Any help or pointers would be much appreciated!

Marko

Okey I think I figured out how to resolve the issue, but the technical reasons remain yet to be determined.
If I remove the return type and then replace .await? with .await.unwrap() it works.
Here is the changed version:

#[tokio::main]
async fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();

    loop {
        let (socket, _) = listener.accept().await?;

        tokio::spawn(async move {
            // Process each socket concurrently.
            process(socket).await
        });
    }
}

The original version actually works fine for me on Windows 11 in both debug and release modes.

Does adding a sleep to the end of the client main change the behavior you're seeing?

I should also say, you definitely are connecting to the (or at least a) server, otherwise the client program wouldn't get a chance to print anything.

1 Like

Hey! Thanks for the answer and I should had specified that the print statement does not print for me ... I will try and do the sleep at the end of the client!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.