From fa02130359f1d1dee44754d639ffbcc159aabad2 Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Sat, 28 Mar 2020 19:10:48 +0200 Subject: [PATCH] examples/tcp_echo_server: cleanup, use defer{} --- examples/tcp_echo_server.v | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/examples/tcp_echo_server.v b/examples/tcp_echo_server.v index c68c7b359d..4f244d0d58 100644 --- a/examples/tcp_echo_server.v +++ b/examples/tcp_echo_server.v @@ -1,22 +1,28 @@ import net - // This file shows how a basic TCP echo server can be implemented using // the `net` module. You can connect to the server by using netcat // or telnet, in separate shells, for example: // `nc 127.0.0.1 12345` // `telnet 127.0.0.1 12345` - fn handle_connection(con net.Socket) { - if _ := con.send_string("Welcome to V's TCP Echo server.\n") { - for { - line := con.read_line() - if line.len == 0 { break } - eprintln('received line: ' + line.trim_space()) - con.send_string(line) or { break } + eprintln('new client connected') + defer { + eprintln('closing connection: $con') + con.close() or { } + } + con.send_string("Welcome to V's TCP Echo server.\n") or { + return + } + for { + line := con.read_line() + if line.len == 0 { + return + } + eprintln('received line: ' + line.trim_space()) + con.send_string(line) or { + return } } - con.close() or {} - return } fn main() { @@ -25,9 +31,9 @@ fn main() { server := net.listen(server_port) or { panic(err) } - for { + for { con := server.accept() or { - server.close() or {} + server.close() or { } panic(err) } go handle_connection(con)