TcpListener vs TcpStream

What is the difference between TcpListener and TcpStream

My understanding is TcpStream for WebSocket!

Tried to test them as below, but the Tcpstream not working with me, I think I've something wrong in the thread.

use std::net::TcpStream;
use std::net::TcpListener;
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:7879").unwrap();

    let mut children = vec![];
    children.push(thread::spawn(move || {
        if let Ok(stream) = TcpStream::connect("127.0.0.1:7879") {
            println!("Connected to the socket!");
        } else {
            println!("Couldn't connect to server...");
        }
    }));

    children.push(thread::spawn(move || {
        for stream in listener.incoming() {
                let stream = stream.unwrap();
        
                println!("Connection established!");
        }
    }));

    for child in children {
        // Wait for the thread to finish. Returns a result.
        let _ = child.join();
    }
}

TcpListener listens on a local port waiting for things to connect to it. TcpStream is the object representing that connection. You can either create a TcpStream by using TcpStream::connect or TcpListener will generate TcpStream objects as things connect to it.

Your example just waits after the first connection because your second thread is waiting indefinitely for new connections and at the end you are waiting for that thread to finish (which it never will) before ending the program. Here's an example of a program that runs once.

Playground

Often with servers though you do want to listen indefinitely, so your existing program would allow you to make a new connection to it from another program if you wanted while the server process still running.

Thanks, how can I make both threads listen indefinitely?

You can keep listening by repeatedly calling TcpListener::accept.

Thanks, what about keeping listening to TcpStream?

You can repeatedly read from the TcpStream using various methods on the Read trait.

1 Like

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.