TcpStream in Rust

TcpStream is a struct in the Rust standard library that represents a stream of bytes over a network connection. It is primarily used for reading and writing data between a client and a server. This struct is part of the std::net module and provides a way to handle TCP connections in a Rust application.

Establishing a TCP Connection

To establish a TCP connection, a client can use the TcpStream::connect method, which attempts to connect to a server at a specified address and port. Below is an example of a simple TCP client that connects to a server running on localhost at port 3000.

Example: Simple TCP Client

Listing 2.3 tcpclient/src/main.rs

use std::net::TcpStream;
 
fn main() {
    let _stream = TcpStream::connect("localhost:3000").unwrap();    #1
}
#1 The TCP client initiates a connection to a remote server running on localhost:3000.

In this example, the client initiates a connection to the server. If the connection is successful, a TcpStream is returned, which can be used for further communication.

Reading and Writing Data

Once a connection is established, the TcpStream can be used to send and receive data. The Read and Write traits from the std::io module are implemented for TcpStream, allowing for reading from and writing to the stream.

Example: Completing the TCP Client

Listing 2.5 Completing the TCP client

use std::io::{Read, Write};
use std::net::TcpStream;
use std::str;
 
fn main() {
    let mut stream = TcpStream::connect("localhost:3000").unwrap();
    stream.write("Hello".as_bytes()).unwrap();       #1
    let mut buffer = [0; 5];
    stream.read(&mut buffer).unwrap();               #2
    println!(
        "Got response from server:{:?}",             #3
        str::from_utf8(&buffer).unwrap()
    );
}
#1 Write a “Hello” message to the TCP server connection.
#2 Read the bytes received from server.
#3 Print out what is received from the server. The server sends raw bytes, and we have to convert them into UTF-8 str type to print them to the terminal.

In this example, the client writes a "Hello" message to the server and then reads the response. The response is printed to the terminal after converting the raw bytes into a UTF-8 string.

Setting Up a TCP Server

On the server side, a TcpListener is used to listen for incoming connections. When a client connects, a TcpStream is provided for communication with that client.

Example: First Iteration of TCP Server

Listing 2.2 First iteration of TCP server (tcpserver/src/main.rs)

use std::net::TcpListener;
 
fn main() {
    let connection_listener = TcpListener::bind(
    "127.0.0.1:3000").unwrap();                      #1
    println!("Running on port 3000");
    for stream in connection_listener.incoming() {     #2
        let _stream = stream.unwrap();                 #3
        println!("Connection established");
    }
}
#1 Initialize a socket server to bind to IP address 127.0.0.1 (localhost) and port 3000.
#2 The socket server waits (listens) for incoming connections.
#3 When a new connection comes in, it is of type Result<TcpStream,Error>, which, when unwrapped, returns a TcpStream if successful, or, in the case of a connection error, exits the program with a panic.

This server listens for incoming connections on localhost:3000 and prints a message when a connection is established.

Example: Completing the TCP Server

Listing 2.4 Completing the TCP server

use std::io::{Read, Write};                          #1
use std::net::TcpListener;
fn main() {
    let connection_listener = TcpListener::bind("127.0.0.1:3000").unwrap();
    println!("Running on port 3000");
    for stream in connection_listener.incoming() {
        let mut stream = stream.unwrap();            #2
        println!("Connection established");
        let mut buffer = [0; 1024];
        stream.read(&mut buffer).unwrap();           #3
        stream.write(&mut buffer).unwrap();          #4
    }
}
#1 TcpStream implements Read and Write traits, so include the std::io module to bring the Read and Write traits into scope.
#2 Make the stream mutable so you can read and write to it.
#3 Read from the incoming stream.
#4 Echo back whatever is received to the client on the same connection.

In this enhanced server example, the server reads data from the client and echoes it back. This demonstrates a simple echo server where the server sends back whatever it receives from the client.

By using TcpStream and TcpListener, Rust provides a robust way to handle TCP connections, enabling the development of networked applications with ease.