diff options
author | Indrajith K L | 2022-12-03 17:00:20 +0530 |
---|---|---|
committer | Indrajith K L | 2022-12-03 17:00:20 +0530 |
commit | f5c4671bfbad96bf346bd7e9a21fc4317b4959df (patch) | |
tree | 2764fc62da58f2ba8da7ed341643fc359873142f /v_windows/v/old/examples/tcp_echo_server.v | |
download | cli-tools-windows-master.tar.gz cli-tools-windows-master.tar.bz2 cli-tools-windows-master.zip |
Diffstat (limited to 'v_windows/v/old/examples/tcp_echo_server.v')
-rw-r--r-- | v_windows/v/old/examples/tcp_echo_server.v | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/v_windows/v/old/examples/tcp_echo_server.v b/v_windows/v/old/examples/tcp_echo_server.v new file mode 100644 index 0000000..e5a0973 --- /dev/null +++ b/v_windows/v/old/examples/tcp_echo_server.v @@ -0,0 +1,40 @@ +import io +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 +// or +// telnet 127.0.0.1 12345 + +fn main() { + mut server := net.listen_tcp(.ip6, ':12345') ? + laddr := server.addr() ? + eprintln('Listen on $laddr ...') + for { + mut socket := server.accept() ? + go handle_client(mut socket) + } +} + +fn handle_client(mut socket net.TcpConn) { + defer { + socket.close() or { panic(err) } + } + client_addr := socket.peer_addr() or { return } + eprintln('> new client: $client_addr') + mut reader := io.new_buffered_reader(reader: socket) + defer { + reader.free() + } + socket.write_string('server: hello\n') or { return } + for { + received_line := reader.read_line() or { return } + if received_line == '' { + return + } + println('client $client_addr: $received_line') + socket.write_string('server: $received_line\n') or { return } + } +} |