-
-
Notifications
You must be signed in to change notification settings - Fork 560
Multiplayer and Networking (FXGL 11)
Almas Baimagambetov edited this page Sep 9, 2020
·
4 revisions
TODO:
Present in FXGL 11.11+.
The fxgl-net
module contains the NetService
API, which can be obtained by calling FXGL.getNetService()
. The service provides developers with the ability to send arbitrary data from one endpoint (e.g. server) to another (e.g. client). Both single and multiple clients are supported. The FXGL networking API provides the same high-level API to both TCP and UDP communications.
Minimal example TCP connection (server):
var server = FXGL.getNetService().newTCPServer(55555);
server.setOnConnected(connection -> {
connection.addMessageHandlerFX((conn, message) -> {
// do something with message when received from client
// FX means this callback runs on JavaFX thread
});
});
server.startAsync();
(TCP client to connect to above server)
var client = FXGL.getNetService().newTCPClient("localhost", 55555);
client.setOnConnected(connection -> {
connection.addMessageHandlerFX((conn, message) -> {
// do something with message when received from server
// FX means this callback runs on JavaFX thread
});
});
client.connectAsync();
You can send data either using a single Connection
object (to that connection), or using the Server
object (to all active connections).
Single connection:
var connnection = ...
var data = new Bundle("");
data.put("key", "value");
connection.send(data);
All active connections:
var server = ...
var data = new Bundle("");
data.put("key", "value");
server.broadcast(data);