#TCP 에코 서버
프로그램 하나가 비어 있는 127.0.0.1 포트에 에코 서버를 띄웁니다. 클라이언트가 줄을 보내고 에코를 다시 읽은 다음 모든 것을 깔끔하게 닫습니다.
#코드
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
#설명
TcpListener를 포트 0에 바인딩하면 OS가 빈 포트를 고르고local_addr()가 실제 주소를 알려 줍니다. 그래서 다른 프로그램과 충돌하지 않습니다.bind와connect는 텍스트,SocketAddr등ToSocketAddrs를 구현한 무엇이든 받습니다(3.2 net,TcpListener).- 서버 스레드는 연결마다 처리 스레드를 하나씩 띄운 뒤 모두
join으로 기다려서 처리한 줄 수를 더합니다. 클로저는listener와conn을 캡처해서 다른 스레드로 가져갑니다(동시성,thread::spawn). - 쓰면서 줄 단위로 읽으려고 소켓을
split()으로 읽기 반쪽과 쓰기 반쪽으로 나누고, 읽기 반쪽을BufReader로 감쌉니다. 각 반쪽은 자기 방향을 소유합니다(반쪽으로 나누기,BufReader). - 소켓은 소유자가 하나하나 닫습니다. 서버 처리기는 두 반쪽을 모두 닫고(
r.into_inner().close(),w.close()), 클라이언트는 쓰기 반쪽을 닫은 뒤using블록을 벗어나며, listener는 모든 클라이언트를 처리한 뒤 닫습니다. 닫기는 실패할 수 있으므로 열어 둔 채 두면 컴파일 에러입니다. - 종료 순서가 중요합니다. 클라이언트는 모두 보낸 뒤 쓰기 반쪽을 닫아 "더 보낼 것 없음"을 알리고(
shutdown(Write)이며 읽기 반쪽은 열려 있음), 서버의lines()는 그 신호로 루프를 끝냅니다. 서버가 두 반쪽을 모두 닫으면 소켓이 닫히고 클라이언트의read_line은 0 바이트를 읽습니다. - 같은 서버를 블로킹 API 대신
accept_async/read_async와 task로 작성할 수도 있습니다(3.2.0 공통 규칙).
잘못된 곳이 있나요? GitHub에서 이 페이지 고치기. 마지막 수정