Merge: GitHub api: Issue events, contributor stats, files
[nit.git] / lib / socket / examples / socket_simple_server.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Simple server example using a non-blocking `TCPServer`
16 module socket_simple_server
17
18 import socket
19
20 if args.is_empty then
21 print "Usage : socket_simple_server <port>"
22 exit 1
23 end
24
25 var port = args[0].to_i
26
27 # Open the listening socket
28 var socket = new TCPServer(port)
29 socket.listen 4
30 socket.blocking = false
31
32 print "Listening on port {socket.port}"
33
34 # Loop until a single client connects
35 var client: nullable TCPStream = null
36 while client == null do
37 printn "."
38 sys.nanosleep(0, 200000)
39
40 client = socket.accept
41 end
42 print " Connected"
43
44 # Communicate
45 print client.read_line
46 client.write "Hello client!\n"
47 print client.read_line
48 client.write "Bye client!\n"
49
50 client.close