std::net 🎯Welcome to another exciting tutorial! Today, we're diving into the world of networking with Rust using the std::net library. This lesson is designed for both beginners and intermediates, so let's get started! 🏃♂️
Networking is the practice of communication between two or more computers or devices over a network, allowing them to exchange data. In our case, we'll be focusing on how to send and receive data over the internet using Rust.
std::net 💡std::net is a part of the Rust standard library that provides low-level networking functionality. It's like the building blocks for creating powerful networking applications in Rust.
Before we dive into the code, make sure you have Rust installed on your system. You can download it from official Rust website.
Let's start with a simple TCP server. TCP (Transmission Control Protocol) is a reliable connection-oriented protocol used extensively on the internet.
use std::io::{self, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
fn handle_client(mut client: TcpStream, client_addr: sockets::SocketAddr) {
let mut buffer = [0; 512];
let mut len = match client.read(&mut buffer) {
Ok(n) => n,
Err(e) => {
println!("Error while reading from client: {}", e);
0
}
};
if len > 0 {
println!("Received {} bytes from client: {}", len, &buffer[..len]);
match client.write(&buffer[..len]) {
Ok(_) => println!("Wrote data to client"),
Err(e) => println!("Error while writing to client: {}", e),
}
}
}
fn main() {
let addr = "(::1):8080"; // Localhost on port 8080
let listener = TcpListener::bind(addr).expect("Failed to bind address");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(|| handle_client(stream, stream.peer_addr().unwrap()));
println!("Connected to client: {}", stream.peer_addr().unwrap());
}
Err(e) => println!("Error accepting connection: {}", e),
}
}
}In this example, we create a simple TCP server that listens for incoming connections on localhost port 8080. When a client connects, it spawns a new thread to handle the client's request. The server reads data from the client, writes it back to the client, and then waits for the next client connection.
Now, let's create a simple TCP client to communicate with our server.
use std::io::{self, Write};
use std::net::TcpStream;
fn main() {
let addr = "(::1):8080"; // Localhost on port 8080
let stream = TcpStream::connect(addr).expect("Failed to connect to server");
writeln!(stream, "Hello, Server!").expect("Failed to write to server");
let mut response = String::new();
stream.read_line(&mut response).expect("Failed to read from server");
println!("Server replied: {}", response);
}In this example, we create a TCP client that connects to our server on localhost port 8080. We send a message "Hello, Server!" to the server and read the server's response.
What is the purpose of the `std::net` library in Rust?
That's it for today! In the next tutorial, we'll dive deeper into networking with Rust, exploring more advanced topics like handling multiple clients, error handling, and more. Until then, keep coding and learning! 💻🚀