create a tcp server on a specific port in rust

To create a TCP server on a specific port in Rust, you can use the std::net module that comes with Rust standard library which provides networking primitives for TCP/UDP connections. Here is an example code for creating a TCP server on port 8000:

main.rs
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};

fn main() {
    // bind the server to the specified address and port
    let listener = TcpListener::bind("127.0.0.1:8000").unwrap();

    // listen for incoming connections
    for stream in listener.incoming() {
        match stream {
            Ok(mut stream) => {
                // handle the client connection
                let mut buffer = [0; 1024];
                stream.read(&mut buffer).unwrap();
                stream.write(b"Hello World!\n").unwrap();
            }
            Err(e) => {
                eprintln!("Error: {}", e);
            }
        }
    }
}
652 chars
23 lines

In this example code, we bind the server to the IP address 127.0.0.1 and port 8000 using TcpListener::bind method. Then, we use a loop to listen for incoming connections using listener.incoming() method which returns an iterator over incoming connections. For each incoming connection, we handle the client connection by reading the data from the client using stream.read method and writing the response back to the client using stream.write method.

Note that this implementation doesn't handle scenarios where the incoming connections are malicious or malformed. It's recommended to have proper error handling, connection pooling, and handling multiple connections simultaneously for a real-world application.

related categories

gistlibby LogSnag