A TCP client connects to a TCP server and exchanges a continuous stream of bytes. In Rust, TcpStream provides the client-side connection, while Read and Write handle data transfer. section 2.2.1 section 2.4
Build a minimal client in an incremental TCP workspace:
- Create a tcpclient binary alongside tcpserver in a Cargo workspace. section 2.2.2
- Connect to localhost:3000 with TcpStream::connect. section 2.2.1 section 2.2.2
- Write text as bytes, read the response into a buffer, and decode it as UTF-8. section 2.2.2
Echo client
A client connects to localhost:3000, writes "Hello" as bytes, reads five response bytes, and prints the returned text. The paired server echoes the same buffer, producing Got response from server:"Hello". section 2.2.2
Listing 2.3 tcpclient/src/main.rs
use std::net::TcpStream;
fn main() {
let _stream = TcpStream::connect("localhost:3000").unwrap(); #1
}
Use the minimal client listing to see the connection-only implementation before adding byte exchange. section 2.2.2
