Each game server (the client) keeps one WebSocket open to the Polychat3 server
(the hub). This file and the payload classes in core change in the same commit.
The protocol is strict: frames are strict JSON, every field is required at every depth and has exactly its listed type, unknown types and fields are errors, and both ends must use the same version.
- WebSocket (RFC 6455) over TCP:
ws://host:port/. The hub listens onbind_addressandserver_portin the hub config,127.0.0.1and 5005 by default. The path is ignored. - The hub itself speaks no TLS. Over
ws://thehandshaketoken travels in clear text, so only use it on one machine or on a private network the game servers share, never on the public internet. - To cross any other network, put a reverse proxy that terminates TLS in front
of the hub. Clients then connect to the proxy with
wss://host:port/and must check its certificate and hostname. The frames are the same either way. - One text frame is one UTF-8 JSON object with a string
type. No batching, no binary frames. - Field names are camelCase, the same as the Java fields.
typeis the class name in camelCase, without itsC2SorS2Cprefix:C2SPlayerJoinisplayerJoin. Protocol.MAX_FRAME_BYTES(1 048 576, 1 MiB) is the largest encoded frame, in both directions. Both ends pass it to Java-WebSocket'sDraft_6455, which closes a connection that receives a bigger frame with 1009. The library only checks what it receives, so the sender keeps its own frames under the limit: the client cutscommandResult.outputand setstruncated: true, and the hub logs an error and does not send a frame of its own that is too big.- One connection per game server for the life of its process. The client sends
from one queue, so
seqis monotonic on the wire.
Every text field is plain text: no § colour codes, no Discord markup, no
prefixes such as [A5]. The sender strips formatting and the receiver adds its
own.
A server id is 1 to 16 characters, each a lowercase letter, a digit, _ or -
(regex ^[a-z0-9_-]{1,16}$). For example a5, gtnh or atm-9. A display
prefix such as [A5] is the id in upper case.
Hub modules that send chat, such as Discord, claim a server id when they load.
The hub loads every module before it accepts connections, and refuses a
handshake that uses a claimed id with 4003. Nothing is hardcoded: with the
Discord module turned off, discord is a normal id.
Everything below is in core, package club.moddedminecraft.polychat3.core.
| Class | Purpose |
|---|---|
Protocol |
VERSION, MAX_FRAME_BYTES, SERVER_ID and the close codes |
payloads.PayloadCodec |
Encodes and decodes frames |
payloads.Payload |
Base class of every frame |
payloads.ProtocolError |
The protocolError frame, used in both directions |
payloads.PlayerInfo, payloads.ServerState |
Shared by both directions |
payloads.ProtocolException |
Thrown for an invalid frame |
payloads.c2s.* |
Frames the client sends; events extend c2s.C2SEvent (adds seq). Every class name starts with C2S |
payloads.s2c.* |
Frames the hub sends; relayed frames extend s2c.S2CRelayed (adds server, serverName). Every class name starts with S2C |
Every payload class and getter has Javadoc.
Using the codec:
String frame = PayloadCodec.encode(payload); // any payload
Payload in = PayloadCodec.C2S.decode(frame); // hub side
Integer version = PayloadCodec.handshakeVersion(frame); // hub side, first frame; null if none
Payload in = PayloadCodec.S2C.decode(frame); // client sidedecode throws ProtocolException for a frame that is not a strict JSON object
(no comments, single quotes, unquoted names or trailing data), or has a missing or
unknown type. It also throws for a field, at any depth, that is missing,
unknown, null, of the wrong JSON type, or an unknown enum value. The receiver
logs a warning and answers with protocolError; see below. encode throws
IllegalArgumentException for a payload with a null field, since that frame
would break the protocol.
seq, lastSeq, session, hubSession and lastRelayed are 64-bit integers. version, online and
maxPlayers are integers. ok, truncated and muted are booleans (muted is an array in muteList). uuid is a dashed
Minecraft UUID. Everything else is a string or an array.
A frame holds no other kind of number, and an integer is written as digits
only, with - in front when it is negative: 1.0, 1e0 and -0 are refused
like a value of the wrong type.
state is one of starting, started, stopping, stopped, crashed,
offline, unresponsive. A client only sends the first five. The hub
refuses a handshake with either of the last two (4000), and logs, acknowledges
and otherwise ignores a serverStatus with one.
| Type | Fields |
|---|---|
handshake |
version, server, name, token, session, state, colour, address, maxPlayers, hubSession, lastRelayed |
heartbeat |
none |
chatMessage |
seq, player, senderId, message |
playerJoin |
seq, player, uuid, online |
playerLeave |
seq, player, uuid, online |
playerList |
seq, players (array of {name, uuid}) |
serverStatus |
seq, state |
commandResult |
seq, id, ok, output, truncated |
mute |
seq, target, muted, by |
protocolError |
code, message |
handshake:sessionis the process start time in ms, set once when the mod loads. A new value tells the hub the server restarted; the same value means a reconnect.stateis the last state the client sent,startingbefore the first.colouris one of the 16 Minecraft colour names.addressandmaxPlayersare shown by/online.hubSessionandlastRelayedask the hub to replay what this server missed; see "Replay to the client". Both are0on the first connection of a session.
heartbeat: sent from the game's server tick every 15 s. Noseq, never buffered or replayed.chatMessage:senderIdis the player's Minecraft UUID.playerJoinandplayerLeave:onlineis the player count afterwards.playerList: the full list, sent after everyhandshakeAcceptedand every 5 minutes.commandResult:idis theidof therunCommandit answers.mute: a staff member on this server muted (muted: true) or unmuted the player with Minecraft UUIDtarget.byis the staff member's UUID, orconsolewhen the server console (or RCON) did it. See "Mutes".
| Type | Fields |
|---|---|
handshakeAccepted |
version, session, lastSeq, servers (array of S2CServerEntry) |
acknowledgement |
seq |
chatMessage |
server, serverName, seq, player, senderId, message |
playerJoin |
server, serverName, seq, player, uuid, online |
playerLeave |
server, serverName, seq, player, uuid, online |
playerList |
server, serverName, seq, players |
serverStatus |
server, serverName, seq, state, colour, address, maxPlayers, players |
runCommand |
id, name, default, args |
systemMessage |
message, kind |
muteList |
muted (array of UUIDs) |
mute |
target, muted, by |
protocolError |
code, message |
handshakeAccepted:sessionis the hub's process start time in ms.lastSeqis the highestseqaccepted from this server and session,0if none. AnS2CServerEntryhasid,name,colour,address,maxPlayers,stateandplayers.acknowledgement: every event up to and includingseqis accepted.chatMessage,playerJoin,playerLeave,playerList,serverStatus: relayed from another server or a module, withserverandserverNamenaming where it came from.seqis the hub's relay number; see "Replay to the client".chatMessage.senderIdis a Minecraft UUID for game chat, and the Discord user id for Discord chat.serverStatusis the origin'sS2CServerEntryflattened onto the frame.
runCommand: the client joinsargswith single spaces and substitutes the result for$argsonce, in its own override fornameif it has one, else indefault(defaultCommandin Java), and trims spaces from both ends, so emptyargsleave no trailing space. It runs that console command and answers withcommandResult.systemMessage:kindisbroadcast,restartorinfo. The hub sends it to every connected game server, or to one server only when it is about that server alone, such as the countdown before its restart.muteList: every muted player's Minecraft UUID, sent right afterhandshakeAccepted. It replaces the client's copy of the list.mute: one player was muted or unmuted, sent to every server.byis a Minecraft UUID for an in-game mute,consolefor one from a server console, or the Discord user id for a Discord one. Not relayed withseqand never replayed: the nextmuteListcarries it.
- The hub owns the mute list, keyed by Minecraft UUID, and keeps it across
restarts. Staff change it in game (c2s
mute) or through a hub module such as Discord. - On every change the hub sends
muteto every connected server, including the one the change came from. Amutethat changes nothing (muting a player who is already muted) sends nothing.muteListand s2cmutecarry UUIDs in lowercase. - The hub ignores a
mutewhosetargetis not a dashed UUID. It still acknowledges it and logs it. - The client keeps its copy from
muteListandmute, and stops a muted player's chat on its own server. - The hub also drops a
chatMessagewhosesenderIdis muted, in case a client's copy is behind. It acknowledges it, logs it and does not relay it.
protocolError has code (machine-readable, for example unsupported_version)
and message (human-readable).
When a frame fails to decode, the receiver logs a warning and sends
protocolError; the connection stays open. Three invalid frames in a row close it
with 4005. Before any protocol close, the hub sends protocolError so the
client's log says why.
A protocolError for a refused handshake never quotes the frame, and the hub
never writes that frame to its log: it holds the token.
- The client opens the socket and sends
handshakeat once, then nothing untilhandshakeAccepted. - A first frame that is not a valid
handshake, or nohandshakewithin 5 s, closes the connection with 4000. - The hub checks, in this order, and closes on the first failure:
- the version equals
Protocol.VERSION(4002). The hub readstypeandversionbefore it decodes the frame, so ahandshakeof another version is closed with 4002 and not 4000, whatever its other fields are; - the id is valid and not claimed by a module (4003);
- the token matches the hub's
server_token, which every server shares (4001).
- the version equals
- If a live connection already has that id, the hub closes the old one with 4004.
- The hub relays the server's
serverStatusto every other server, so a server they sawofflineorunresponsive, or never saw, shows its handshake state again. It answershandshakeAccepted, then replays what the client missed; see "Replay to the client". - The client resends its buffered events with
seqabovelastSeq, oldest first, then sends a freshplayerList.
version is one integer, Protocol.VERSION. Both ends must use exactly the
same version.
It stays 1 until the first release. From then on, any change to the protocol,
including a new type, bumps it by one in the next release.
- Events are
chatMessage,playerJoin,playerLeave,playerList,serverStatus,commandResultandmute. Each carriesseq: 1 for the first event a client process sends, plus one for every event after it. seqbelongs to the session. After a restart the client has a newsessionand starts again at 1, and the hub starts counting again from 0.- The hub sends
acknowledgementafter it has processed an event. Oneacknowledgementmay cover several events. - The client buffers every
chatMessage,playerJoin,playerLeave,serverStatusandmuteuntil anacknowledgementcovers it, up to 200 events, dropping the oldest when full.playerListandcommandResultare not buffered. - An event with
seqat or below the hub's last acceptedseqfor that session is a duplicate. The hub acknowledges it again and does not process it. - Delivery is at-least-once.
- The hub numbers every relayed event with one
seqfor the whole hub: 1 for the first event it relays after it starts, plus one for every event after that. An event has the sameseqon every server it goes to, so a client sees gaps, which are normal. - The hub keeps the last 200 relayed
chatMessage,playerJoinandplayerLeaveframes.playerListandserverStatusare not kept, sincehandshakeAccepted.serversalready carries the current state. - The client keeps, in memory, the hub
sessionfrom its lasthandshakeAcceptedand the highest relayedseqit has received since. - When it reconnects in the same session, the client sends them as
hubSessionandlastRelayed. IfhubSessionequals the hub'ssession, the hub sends every kept frame withseqabovelastRelayedthat came from another server, oldest first, right afterhandshakeAccepted. - On the first connection of a session, after a restart, the client sends
0for both and gets no replay: no players were online to miss anything. A hub that restarted has a newsession, so it replays nothing either. - Frames older than the last 200 are lost.
- On a stop, the client sends
serverStatusstopped; on a crash,crashed, from a JVM shutdown hook (it runs on a normal exit, Ctrl+C and SIGTERM). - The client then holds the JVM's shutdown until an
acknowledgementcovers thatserverStatus, for at most 3 s, and closes the connection with 1000 either way. If the hub is unreachable, the JVM exits after 3 s and the hub sees a dropped connection, marking the serveroffline. - When a connection closes, for any reason, the hub marks the server
offlineand relays thatserverStatus, unless the server last reportedstoppedorcrashed: that state stays, and the other servers already have it. A connection replaced by a newer one (4004) changes nothing. - A server that is
stopped,crashedorofflinehas no players: the hub empties its player list when it takes that state, since a game that shuts down may send noplayerLeavefor the players it kicks. The relayedserverStatusalready carries the empty list. - The hub keeps a server's last
seqafter any close. The restarted server's newsessionresets it to 0, so both ends start again from the beginning. - A process killed without shutdown hooks (
kill -9, the OOM killer, power loss) sends nothing and looks like a dropped connection. The newsessionin its nexthandshakeis what tells the hub it restarted.
- Socket. Both ends ping every 30 s. No pong within 45 s closes the connection locally with 1006.
- Game thread. The client sends
heartbeatevery 15 s from a game-thread timer, so it stops when the game thread hangs. If the hub sees noheartbeator event for 45 s, it marks the serverunresponsiveand relays thatserverStatus. The socket stays open. Only astartedorstoppingserver is marked: one instartingsends no heartbeat while it loads, which for a modded server can take minutes. The next heartbeat or event restores the last state the client reported.
| Code | Constant | Meaning | Client does |
|---|---|---|---|
| 1000 | CLOSE_NORMAL |
Client shutting down, after serverStatus stopped or crashed |
Nothing |
| 1001 | CLOSE_GOING_AWAY |
Hub shutting down or restarting | Reconnect with backoff |
| 1006 | No pong in time; local only | Reconnect with backoff | |
| 1009 | CLOSE_TOO_BIG |
Frame larger than MAX_FRAME_BYTES |
Log at error, reconnect |
| 4000 | CLOSE_BAD_HANDSHAKE |
First frame not a valid handshake, or none in time |
Reconnect with backoff |
| 4001 | CLOSE_BAD_TOKEN |
Wrong token | Log at error, retry every 60 s |
| 4002 | CLOSE_BAD_VERSION |
Version differs from the hub's | Log at error, retry every 60 s |
| 4003 | CLOSE_BAD_SERVER_ID |
Invalid server id, or one a module claimed | Log at error, stop |
| 4004 | CLOSE_REPLACED |
Replaced by a newer connection with the same id | Log at error, stop |
| 4005 | CLOSE_PROTOCOL_ERROR |
Binary frame, or three invalid frames in a row | Reconnect with backoff |
Backoff is 1, 2, 4, 8, 16, then 30 s, with 20 % jitter.
> is client to hub, < is hub to client.
> {"type":"handshake","version":1,"server":"a5","name":"All the Mods 5","token":"...","session":1793130000000,"state":"started","colour":"yellow","address":"a5.example.net","maxPlayers":40,"hubSession":0,"lastRelayed":0}
< {"type":"handshakeAccepted","version":1,"session":1793120000000,"lastSeq":0,"servers":[{"id":"gtnh","name":"GTNH","colour":"gold","address":"gtnh.example.net","maxPlayers":30,"state":"started","players":[{"name":"Steve","uuid":"069a79f4-..."}]}]}
< {"type":"muteList","muted":["1f2a3b4c-..."]}
> {"type":"playerList","players":[{"name":"Alex","uuid":"ec561538-..."}],"seq":1}
< {"type":"acknowledgement","seq":1}
> {"type":"chatMessage","player":"Alex","senderId":"ec561538-...","message":"hello!","seq":2}
< {"type":"acknowledgement","seq":2}
> {"type":"mute","target":"ec561538-...","muted":true,"by":"069a79f4-...","seq":3}
< {"type":"mute","target":"ec561538-...","muted":true,"by":"069a79f4-..."}
< {"type":"acknowledgement","seq":3}
> {"type":"heartbeat"}
> {"type":"serverStatus","state":"stopping","seq":4}
< {"type":"runCommand","id":"c-7","name":"tps","default":"forge tps","args":[]}
> {"type":"commandResult","id":"c-7","ok":true,"output":"Overall: Mean TPS: 20.0","truncated":false,"seq":5}
< {"type":"systemMessage","message":"Server restarting in 60 s","kind":"restart"}
< {"type":"chatMessage","player":"Alex","senderId":"ec561538-...","message":"hello!","server":"a5","serverName":"All the Mods 5","seq":41}
< {"type":"chatMessage","player":"Heather","senderId":"123456789012345678","message":"hi from Discord","server":"discord","serverName":"Discord","seq":42}
< {"type":"protocolError","code":"unknown_type","message":"unknown type pong"}