SpiderMonkey: Multi-Player Networking

This document introduces you to the SpiderMonkey networking API. A multi-player game is made up of clients and a server.

Each Client informs the Server about its player's moves and actions. The Server centrally collects the game state and broadcasts the state info back to all connected clients. This way all clients share the same game world and can display it to their players from their perspective.

SpiderMonkey API Overview

The SpiderMonkey API is a set of interfaces and helper classes in the 'com.jme3.network' package. For most users, this package and the 'message' package is all they need to worry about. (The 'base' and 'kernel' packages only come into play when implementing custom network transports or alternate client/server protocols, which is now possible).

The SpiderMonkey API assists you in creating a Server, Clients, and Messages. Once a Server instance is created and started, the Server accepts remote connections from Clients, and you can send and receive Messages. Client objects represent the client-side of the client-server connection. Within the Server, these Client objects are referred to as HostedConnections. HostedConnections can hold application-defined client-specific session attributes that the server-side listeners and services can use to track player information, etc.

Seen from the Client Seen from the Server
com.jme3.network.Client == com.jme3.network.HostedConnection

You can register several types of listeners to be notified of changes.

Client and Server

Creating a Server

A com.jme3.network.Server is a headless com.jme3.app.SimpleApplication. Headless means that the update loop runs, but the application does not open a window and does not listen to direct user input.

ServerMain app = new ServerMain();
app.start(JmeContext.Type.Headless);

Create a Server in the simpleInitApp() method and specify a communication port, for example 6143.

Server myServer = Network.createServer(6143);
myServer.start();

The server is ready to accept clients. Let's create one.

Creating a Client

A com.jme3.network.Client is a standard com.jme3.app.SimpleApplication.

ClientMain app = new ClientMain();
app.start(JmeContext.Type.Display); // standard type

Create a Client in the simpleInitApp() method and specify the servers IP address, and the same communication port as for the server, here 6143.

Client myClient = Network.connectToServer("localhost", 6143);
myClient.start();

The server address can be in the format "localhost", "127.0.0.1" (for local testing) or “123.456.78.9” (the IP address of a real server).

Getting Info About a Client

The server refers to a connected client as com.jme3.network.HostedConnection. The server can get info about clients as follows:

AccessorPurpose
myServer.getConnection(0)Server gets the first etc connected HostedConnection object.
myServer.getConnections()Server gets a collection of all connected HostedConnection objects.
myServer.getConnections().size()Server gets the number of all connected HostedConnection objects.

Your game can define its own player ID based on whatever user criteria you want. If the server needs to look up player/client-specific information, it can store this information directly on the HostedConnection object:

AccessorPurpose
conn.setAttribute("MyState", new MyState()); Server can change an attribute of the HostedConnection.
MyState state = conn.getAttribute("MyState") Server can read an attribute of the HostedConnection.

Messaging

Creating Message Types

Each message represents data you want to transmit, for instance transformation updates or game actions. For each message type, create a message class that extends com.jme3.network.AbstractMessage. Use the @Serializable annotation from com.jme3.network.serializing.Serializable and create an empty default constructor. Custom constructors, fields, and methods are up to you and depend on the message data that you want to transmit.

@Serializable
public class HelloMessage extends AbstractMessage {
  private String hello;       // message data
  public HelloMessage() {}    // empty constructor
  public HelloMessage(String s) { hello = s; } // custom constructor
}

Register each message type to the com.jme3.network.serializing.Serializer, in both server and client.

Serializer.registerClass(HelloMessage.class);

Reacting to Messages

After a message was received, a listener responds to it. The listener can access fields of the message, and send messages back. Implement responses in the two Listeners’ messageReceived() methods for each message type.

ClientListener.java

Create one ClientListener.java and make it extend com.jme3.network.MessageListener.

public class ClientListener implements MessageListener<Client> {
  public void messageReceived(Client source, Message message) {
    if (message instanceof HelloMessage) {
      // do something with the message
      HelloMessage helloMessage = (HelloMessage) message;
      System.out.println("Client #"+source.getId()+" received: '"+helloMessage.getSomething()+"'");
    } // else...
  }

For each message type, register a client listener to the client.

myClient.addMessageListener(new ClientListener(), HelloMessage.class);

ServerListener.java

Create one ServerListener.java and make it extend com.jme3.network.MessageListener.

public class ServerListener implements MessageListener<HostedConnection> {
  public void messageReceived(HostedConnection source, Message message) {
    if (message instanceof HelloMessage) {
      // do something with the message
      HelloMessage helloMessage = (HelloMessage) message;
      System.out.println("Server received '" +helloMessage.getSomething() +"' from client #"+source.getId() );
    } // else....
  }

For each message type, register a server listener to the server:

myServer.addMessageListener(new ServerListener(), HelloMessage.class);

Creating and Sending Messages

A client can send a message to the server:

Message message = new HelloMessage("Hello World!");
myClient.send(message);

The server can broadcast a message to all HostedConnection (clients):

Message message = new HelloMessage("Welcome!");
myServer.broadcast(message);

Using com.jme3.network.Filters, the server can send a message to specific HostedConnection (conn1, conn2, conn3), or to all but a few HostedConnections (not to conn4).

myServer.broadcast( Filters.in( conn1, conn2, conn3 ), message );
myServer.broadcast( Filters.notEqualTo( conn4 ), message );

Identification and Rejection

The ID of the Client and HostedConnection are the same at both ends of a connection. The ID is given out authoritatively by the Server.

... myClient.getId() ...

A server has a game version and game name. Each client expects to communicate with a server with a certain game name and version. Test first whether the game name matches, and then whether game version matches, before sending any messages! If they do not match, you should refuse to connect, because the client and server will not be able to communicate.

AccessorPurpose
myServer.setName() Specify the game name (free-form String)
myServer.setVersion() Specify the game version (int)
myClient.getGameName() Client gets the name of the server it is connected to.
myClient.getVersion() Client gets the version of the server it is connected to.

Tip: Your game defines its own attributs, such as player ID, based on whatever criteria you want. If you want to look up player/client-specific information, you can set this information directly on the Client/HostedConnection (see Getting Info About a Client).

Closing Clients and Server Cleanly

Closing a Client

You must override the client's destroy() method to close the connection cleanly when the player quits the client:

  @Override
  public void destroy() {
      myClient.close();
      super.destroy();
  }

Closing a Server

You must override the server's destroy() method to close the connection when the server quits:

  @Override
  public void destroy() {
      myServer.close();
      super.destroy();
  }

Kicking a Client

The server can kick a HostedConnection to make it disconnect. You should provide a String with further info (an explanation to the user what happened) for the server to send along. This info message can be used (displayed to the user) by a ClientStateListener. (See below)

conn.close("We kick cheaters.");

Listening to Connection Notification

The server and clients are notified about connection changes.

ClientStateListener

The com.jme3.network.ClientStateListener notifies the Client when the Client has fully connected to the server (including any internal handshaking), and when the Client is kicked (disconnected) from the server.

ClientStateListener interface Purpose
clientConnected(Client c) Implement here what happens as soon as this clients has fully connected to the server.
clientDisconnected(Client c, DisconnectInfo info) Implement here what happens after the server kicks this client. For example, display the DisconnectInfo to the user.

Implement the ClientStateListener interface in the Client, and then register it:

myClient.addClientStateListener(this);

ConnectionListener

The com.jme3.network.ConnectionListener notifies the Server whenever new HostedConnections (clients) come and go. The listener notifies the server after the Client connection is fully established (including any internal handshaking).

ConnectionListener interface Purpose
connectionAdded(Server s, HostedConnection c) Implemenent here what happens after a new HostedConnection has joined the Server.
connectionRemoved(Server s, HostedConnection c) Implement here what happens after a HostedConnection has left. E.g. a player has quit the game and the server removes his character.

Implement the ConnectionListener in the Server, and register it.

myServer.addConnectionListener(this);

UDP versus TCP

SpiderMonkey supports both UDP (unreliable, fast) and TCP (reliable, slow) transport of messages.

message1.setReliable(true); // TCP
message2.setReliable(false); // UDP

Important: Use Multi-Threading

You cannot modify the scenegraph in the NetworkThread. You have to create a Callable, enqueue the Callable in the OpenGLThread, and the callable makes the modification in the correct moment. A Callable is a Java class representing a (possibly time-intensive), self-contained task.

app.enqueue(callable);

Learn more about multithreading here.

documentation, network, spidermonkey

view online version