Skip to content

Listeners

mega12345mega edited this page Jan 25, 2023 · 2 revisions

Listeners are called in parallel on separate threads. Packet handling will wait until all the listeners have either completed or have called WaitState#dontWait().

Packet listeners

Packet listeners are called when a packet is received by a Connection. If the received packet is a reply, it will get passed on to the response listener if there is one. Otherwise, it will get handled by the normal packet listeners. Packet listeners take in the Packet, Connection, and WaitState.

Example:

server.addPacketListener((packet, conn, wait) -> {
    conn.reply(packet, new PrimitivePacket("Received packet of type: " + packet.getClass().getName()));
});

client.sendPacket(new NamePacket("Fred"), (response, conn, wait) -> {
    System.out.println(response.getValue()); // Prints: Received packet of type: example.NamePacket
});

TypedPacketListener

Use the TypedPacketListener to handle specific packet types.

Example:

client.addPacketListener(new TypedPacketListener()
        .when(NamePacket.class, (namePacket, conn, wait) -> {
            System.out.println("Renamed to: " + namePacket.getName());
        })
        .when(DisconnectPacket.class, (disconnectPacket, conn, wait) -> {
            System.out.println("Disconnected due to: " + disconnetPacket.getReason());
            conn.close();
        }));

Connection listeners

Connection listeners are called on the server when a client connects. It takes in the ServerConnection and WaitState. Even before the listeners have completed, Server#getConnections() will include the connection, and Server#sendPacket will send packets to it.

Example:

server.addConnectionListener((conn, wait) -> {
    String name = ((NamePacket) conn.sendPacketWithResponse(new NameRequestPacket())).getName();
    server.sendPacket(new PlayerConnectedPacket(name));
});
// When a client connects:
// Server -> Client: NameRequestPacket
// Server <- Client: NamePacket(name)
// Server -> All Clients: PlayerConnectedPacket(name)

Clone this wiki locally