So far, we've learned the basics to set up a server and connecting a client. However, they don't do much, so let's look into what it takes to get them to communicate with each other.
In SpiderMonkey, communication is handled via messaging and the message interface. When a server sends a message, it uses the broadcast()
method, while a client uses send()
. The side that is supposed to receive the message has to have a suitable MessageListener
class. To try all these things out, let's have our server greet the connecting player by sending them a message, which will be displayed once received.
Perform the following steps to connect and handle basic messaging:
@Serializable() public class ServerMessage extends AbstractMessage{ private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
MessageListener
. It's a very simple class that will print the message to the console when received, as follows:public class ServerMessageHandler implements MessageListener<Client>{ public void messageReceived(Client source, Message m) { ServerMessage message = (ServerMessage) m; System.out.println("Server message: " + message.getMessage()); } }
ServerMessageHandler
and add it to the client, telling it to only listen for ServerMessages
, as follows:ServerMessageHandler serverMessageHandler = new ServerMessageHandler(); client.addMessageListener(serverMessageHandler, ServerMessage.class);
It is also possible to let ServerMessageHandler
handle all incoming messages by using the following line of code:
client.addMessageListener(serverMessageHandler);
ServerMessage connMessage = new ServerMessage(); String message = "Player connected from: " + conn.getAddress(); connMessage.setMessage(message); server.broadcast(connMessage);
public static void main(String[] args ) throws Exception { Serializer.registerClass(ServerMessage.class);
Spending time and defining what messages should contain is a good way to get a grip of the project as a lot of the architecture will revolve around them. The message we created in this recipe is called ServerMessage
, because it is used to send a lot of information from the server to the client.
The next class we created was MessageListener
. The only thing it does upon receiving the message is print it to the console. We added it to the client, and also stated that it should specifically listen for ServerMessages
.
By default, calling broadcast
will send the message to all the connected clients. In this case, we just want to send a message to a specific client or a group of clients (like a team). Broadcast can also be called with Filter
. It can also send messages to a specific channel, to which a team or group of players might be assigned.
3.148.117.212