WebSocket server

com.server.protocol.WebSocket

The websocket block starts a WebSocket server implemented from RFC 6455 in com.server.protocol.WebSocket: the upgrade handshake, masked and fragmented frames of any length, text and binary messages, ping/pong and the closing handshake.

A handler

public class Lobby extends WebSocket {

    public Lobby(int port) { super(port); }

    @Override
    public void onOpen(ServerConnection c) {
        c.sendMessage("welcome " + (c.getUser() != null ? c.getUser() : "guest"));
    }

    @Override
    public void processCustomMessage(ServerConnection c, String message) {
        if (message.startsWith("say "))
            getServer().broadcast(c.getConnectionID() + ": " + message.substring(4));
    }

    @Override
    public void onClose(ServerConnection c) {
        getServer().broadcast(c.getConnectionID() + " left");
    }
}
websocket:
listen 8081
handler com.example.Lobby
origin example.com

Hooks

OverrideCalled when
onOpen(c)The handshake has completed.
processCustomMessage(c, text)A text message arrived. Without an override the server echoes it.
processBinaryMessage(c, bytes)A binary message arrived.
onClose(c)The connection ended, for any reason. Called exactly once.

Sending

CallSends
c.sendMessage(text)A text message to one client.
sendBytes(c, bytes)A binary message.
getServer().broadcast(text)A text message to every client of this server.
getServer().getConnections()The open connections, to pick recipients yourself.
close(c, 1000)A close frame with a status code, then disconnects.

All of these are safe from any thread, so a game loop or a database callback can send without ceremony.

Per-connection state

c.set("room", "lobby");
String room = c.getString("room");

Remove what you stored in onClose if anything else holds a reference to it.

Who is connected

The handshake is an HTTP request, so it carries cookies. If the browser has a JBend session cookie (the user logged in through /api/login on the same site) the connection already knows its account: c.getUser(). To check a username and password sent over the socket instead, use LoginHandler.verify; see Accounts.

Origins

Any web page can open a WebSocket to any server, and the browser will send your site's cookies with it. origin example.com refuses handshakes from pages on other sites. Set it on any socket that trusts the session cookie. Clients that are not browsers send no Origin header and are let through; use a login message for those.

Keeping connections alive

The server pings each client every 25 seconds (ping), which stops proxies from closing a quiet connection. Browsers answer pings by themselves. idle 10m closes clients that have sent no message for that long; pongs do not count. A client that connects and never completes the handshake is dropped after 10 seconds.

Limits

An example message format

WebSocket gives you messages; what is in them is up to you. JBGame uses short text commands, which are easy to read in the browser's network tab:

client: game::14::join:kane&pw      server: welcome:3:kane
client: game::9::key:right          server: updatepos:111,815,0
client: game::10::chat:hello        server: chat:kane:hello