gamnit: add server discovery or create example
[nit.git] / lib / gamnit / network / network.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 # Easy client/server logic for games and simple distributed applications
16 #
17 # Both `gamnit::client` and `gamnit::server` can be used separately or
18 # together by importing `gamnit::network`.
19 # Use both modules to create an program that discover local servers
20 # or create one if none is found:
21 #
22 # ~~~
23 # redef fun handshake_app_name do return "network_test"
24 #
25 # # Discover local servers
26 # var servers = discover_local_servers
27 # if servers.not_empty then
28 # # Try to connect to the first local server
29 # var server_info = servers.first
30 # var server = new RemoteServer(server_info)
31 #
32 # if not server.connect then
33 # print_error "Failed to connect to {server_info.address}:{server_info.port}"
34 # else if not server.handshake then
35 # print_error "Failed handshake with {server_info.address}:{server_info.port}"
36 # else
37 # # Connected!
38 # print "Connected to {server_info.address}:{server_info.port}"
39 #
40 # # Write something and close connection
41 # server.writer.serialize "hello server"
42 # server.socket.as(not null).close
43 # end
44 # else
45 # # Create a local server
46 # var connect_port = 33729
47 # print "Launching server: connect on {connect_port}, discovery on {discovery_port}"
48 # var server = new Server(connect_port)
49 #
50 # # Don't loop if testing
51 # if "NIT_TESTING".environ == "true" then exit 0
52 #
53 # loop
54 # # Respond to discovery requests
55 # server.answer_discovery_requests
56 #
57 # # Accept new clients
58 # var new_clients = server.accept_clients
59 # for client in new_clients do
60 # # Read something and close connection
61 # assert client.reader.deserialize == "hello server"
62 # client.socket.close
63 # end
64 # end
65 # end
66 # ~~~
67 module network
68
69 import server
70 import client