From 801917f8fcd4d9c653b250b4578b354f47092018 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Alexis=20Laferri=C3=A8re?= Date: Sun, 21 Dec 2014 23:40:04 -0500 Subject: [PATCH] lib/socket: add an easier server example MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Alexis Laferrière --- lib/socket/examples/socket_simple_server.nit | 50 ++++++++++++++++++++++++++ tests/sav/socket_simple_server.res | 1 + 2 files changed, 51 insertions(+) create mode 100644 lib/socket/examples/socket_simple_server.nit create mode 100644 tests/sav/socket_simple_server.res diff --git a/lib/socket/examples/socket_simple_server.nit b/lib/socket/examples/socket_simple_server.nit new file mode 100644 index 0000000..54f9ea3 --- /dev/null +++ b/lib/socket/examples/socket_simple_server.nit @@ -0,0 +1,50 @@ +# This file is part of NIT ( http://www.nitlanguage.org ). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Simple server example using a non-blocking `TCPServer` +module socket_simple_server + +import socket + +if args.is_empty then + print "Usage : socket_simple_server " + exit 1 +end + +var port = args[0].to_i + +# Open the listening socket +var socket = new TCPServer(port) +socket.listen 4 +socket.blocking = false + +print "Listening on port {socket.port}" + +# Loop until a single client connects +var client: nullable TCPStream = null +while client == null do + printn "." + sys.nanosleep(0, 200000) + + client = socket.accept +end +print " Connected" + +# Communicate +print client.read_line +client.write "Hello client!\n" +print client.read_line +client.write "Bye client!\n" + +client.close diff --git a/tests/sav/socket_simple_server.res b/tests/sav/socket_simple_server.res new file mode 100644 index 0000000..1ff31ed --- /dev/null +++ b/tests/sav/socket_simple_server.res @@ -0,0 +1 @@ +Usage : socket_simple_server -- 1.7.9.5