create a tcp client on a specific port in rust

Here's an example of how to create a TCP client in Rust that connects to a server on a specific port:

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

// Connect to a server on a specific host and port
let mut stream = TcpStream::connect("127.0.0.1:8080").expect("Could not connect to server");

// Send data to the server
let message = "Hello, server!";
stream.write_all(message.as_bytes()).expect("Failed to send message");

// Receive data from the server
let mut buffer = [0; 512];
stream.read(&mut buffer).expect("Could not read from server");
let received = String::from_utf8_lossy(&buffer[..]);
println!("Received from server: {}", received);
553 chars
16 lines

This code uses the TcpStream type from the standard library to connect to a server at 127.0.0.1:8080. After establishing a connection, it sends a message to the server using the write_all method, and then receives a response using the read method.

related categories

gistlibby LogSnag