本页尚未翻译,以下为英文原文。
#TCP echo server
本页内容
One program starts an echo server on a free 127.0.0.1 port, has clients send lines and read back the echoes, and then shuts everything down cleanly.
#Code
nabi
// A line-based TCP echo server and its clients in one program.
use std::net::{TcpListener, TcpStream, SocketAddr};
use core::io::{IoError, BufReader};
use std::thread;
// Echo every line of one connection back until the client closes its side.
fn serve(conn: TcpStream) throws (IoError) -> i32 {
let lines = 0;
let (rh, w) = conn.split();
let r = BufReader::new(rh);
try for line in r.lines() {
try w.write_all(f"echo: {line}\n");
lines += 1;
}
// Both halves closed: the socket closes and the client sees EOF.
try r.into_inner().close();
try w.close();
lines
}
// Send each message, wait for its echo, then close the write side.
fn client(id: i32, addr: SocketAddr, msgs: List<str>) throws (IoError) {
let (rh, w) = (try TcpStream::connect(addr)).split();
using r = BufReader::new(rh) {
for m in msgs {
try w.write_all(f"{m}\n");
let reply = StrBuf::new();
try r.read_line(reply);
println(f"client {id}: sent {m:?}, got {reply.to_str().trim_end():?}");
}
// Closing the write half ends the stream for the server.
try w.close();
// A read of 0 bytes means the server closed the connection.
if (try r.read_line(StrBuf::new())) == 0 { println(f"client {id}: closed"); }
}
}
fn main() throws (IoError) {
// Port 0: the OS picks a free port; local_addr tells us which.
let listener = try TcpListener::bind("127.0.0.1:0");
let addr = try listener.local_addr();
let clients = 3;
// The server thread accepts `clients` connections, one handler thread each.
let server = thread::spawn(|| {
let handlers: List<thread::JoinHandle<i32>> = [];
for _ in 0..clients {
let (conn, _peer) = try! listener.accept();
handlers.push(thread::spawn(|| try serve(conn) catch e { println(f"server: {e}"); 0 }));
}
let total = 0;
for h in handlers { total += try! h.join(); }
try! listener.close();
total
});
try client(1, addr, ["hello", "nabi"]);
try client(2, addr, ["one line"]);
try client(3, addr, ["a", "b", "c"]);
let served = try! server.join();
println(f"server echoed {served} lines and stopped");
}
client 1: sent "hello", got "echo: hello"
client 1: sent "nabi", got "echo: nabi"
client 1: closed
client 2: sent "one line", got "echo: one line"
client 2: closed
client 3: sent "a", got "echo: a"
client 3: sent "b", got "echo: b"
client 3: sent "c", got "echo: c"
client 3: closed
server echoed 6 lines and stopped
#Walkthrough
- Binding
TcpListenerto port 0 lets the OS choose a free port, andlocal_addr()reports the actual address, so there is no clash with other programs.bindandconnecttake text, aSocketAddror anything else that implementsToSocketAddrs(3.2 net,TcpListener). - The server thread starts one handler thread per connection, then
joins them all and adds up the lines served. The closures capturelistenerandconnand carry them to the other threads (Concurrency,thread::spawn). - To read line by line while writing, the socket is
split()into a read half, wrapped in aBufReader, and a write half: each half owns its direction (split halves,BufReader). - Every socket is closed by its owner: the server handler closes both halves (
r.into_inner().close(),w.close()), the client closes its write half and leaves itsusingblock, the listener once all clients are served. Leaving one open is a compile error, since its close can fail. - Shutdown order matters. After sending everything, the client closes its write half to say "nothing more" (a
shutdown(Write), the read half stays open), and the server'slines()ends its loop on that signal. Once the server closes both halves, the socket closes and the client'sread_linereads 0 bytes. - The same server can be written with
accept_async/read_asyncand tasks instead of the blocking API (3.2.0 common rules).
Found a mistake? Edit this page on GitHub. Last updated