Merge: gamnit::network: add server discovery via UDP
authorJean Privat <jean@pryen.org>
Tue, 6 Jun 2017 15:48:00 +0000 (11:48 -0400)
committerJean Privat <jean@pryen.org>
Tue, 6 Jun 2017 15:48:00 +0000 (11:48 -0400)
commitf9969fb1118e7a60fd92f2d62a52309312ded6aa
tree020725f56886a5ebe32d611abf057d686a20022c
parentb8659b5e5efc7cd58248f115a9868872be4a46e3
parent76e4234164b203dacf4b8f58554d8c41be4a5288
Merge: gamnit::network: add server discovery via UDP

Move server discovery logic from Tinks! up to `gamnit::network` and extend existing services with more options. These new services allow for an easy discovery of local servers over UDP, as in the following example which also creates a server if none is found:

~~~nit
import gamnit::network

# Discover local servers
var servers = discover_local_servers
if servers.not_empty then
# Try to connect to the first local server
var server_info = servers.first
var server = new RemoteServer(server_info)

if not server.connect then
print_error "Failed to connect to {server_info.address}:{server_info.port}"
else if not server.handshake then
print_error "Failed handshake with {server_info.address}:{server_info.port}"
else
# Connected!
print "Connected to {server_info.address}:{server_info.port}"

# Write something and close connection
server.writer.serialize "hello server"
server.socket.as(not null).close
end
else
# Create a local server
var connect_port = 38271
print "Launching server: connect on {connect_port}, discovery on {discovery_port}"
var server = new Server(connect_port)

# Don't loop if testing
if "NIT_TESTING".environ == "true" then exit 0

loop
# Respond to discovery requests
server.answer_discovery_requests

# Accept new clients
var new_clients = server.accept_clients
for client in new_clients do
# Read something and close connection
assert client.reader.deserialize == "hello server"
client.socket.close
end
end
end
~~~

Pull-Request: #2470
Reviewed-by: Jean-Christophe Beaupré <jcbrinfo.public@gmail.com>