Inter-module Communication

Server modules and room modules can communicate with each other using custom events and method calls. The following sections demonstrate.

Communicating with a specific server module

To communicate with a server module from a room module or another server module, retrieve a reference to the Server instance, then retrieve the desired server module via the Server class's getModule() method, and invoke the desired method on the server module. For example,

((MyServerModule)moduleContext.getServer().getModule("MyServerModule")).someMethod();

In the preceding code, getModule("MyServerModule") refers to the module by ID. Notice the cast to the module type, MyServerModule, which is required because the getModule() method's return type is the interface Module.

Communicating with a single room's room modules

To communicate with a specific room's room modules, dispatch a custom event via the desired Room instance, and listen for that event in the corresponding room modules. For example, the following code, excerpted from a server module, dispatches MY_CUSTOM_EVENT through the room with the ID "Lobby":

Room room = moduleContext.getServer().getRoom("Lobby");
room.dispatchEvent("MY_CUSTOM_EVENT", new RoomEvent(room, null, null));

To respond to the custom event, any room module associated with the "Lobby" room can register a listener for the MY_CUSTOM_EVENT event:

public boolean init (ModuleContext ctx) {
  ctx.getRoom().addEventListener("MY_CUSTOM_EVENT", this, "onMyCustomEvent");
}

public void onMyCustomEvent (Event evt) {
  // Respond to event here
}

Notice that listeners for custom events are passed an object of type Event rather than a concrete class such as RoomEvent. Listeners for custom events are expected to cast Event to the appropriate concrete class as needed.

Communicating with all modules

To communicate with every server module, and every room module for every Room instance on the server, dispatch a custom event via the Server instance, and listen for that event in the desired modules. For example, the following code, excerpted from a room module, dispatches MY_CUSTOM_EVENT through the server:

ctx.getServer().dispatchEvent("CUSTOM_EVENT", new ServerEvent(null, null));

To respond to the custom event, any module can register a listener for the MY_CUSTOM_EVENT event:

public boolean init (ModuleContext ctx) {
  ctx.getServer().addEventListener("MY_CUSTOM_EVENT", this, "onMyCustomEvent");
}