Game servers
A game server is an optional program of your own that runs a game's rules on the server side: a referee that checks moves, hidden information such as a card game's hands, or a whole persistent world. Write one in any language. SDKs exist for Go, Python and C++, and the protocol is plain JSON lines over TLS, so other languages need no SDK.
The model
- The server connects out. It opens a TLS connection to the hub and logs in with its game's id and server key. It needs no open ports or fixed address, so it can run on your own computer or any cloud machine, and use whatever else it likes: databases, files, other services.
- One connection per game. A second login with the same key replaces the first.
- Timers are yours. They run in your process, at any resolution.
- Key what you keep by player id. Each player has a permanent id that never changes; handles can be renamed.
A game's registration sets its server mode. Only observe and
authority games take a server:
| Mode | Players' ALL, TELL, frames and TURN |
Results |
|---|---|---|
relay |
Relayed between players. No server | The players' END reports |
observe |
Relayed between players as in relay mode; the server gets a copy | The server's |
authority |
Go only to the server, which sends players what they should see | The server's |
In both server modes, TELL,0 goes to the server, SAY reaches the players
and the server hears it, and players' END reports only ask the server for
the result. A world game is always in authority mode.
Server keys
Make a key on your game's settings page, in the game server section, which
appears for observe and authority games. The page also shows whether your
server is connected.
- A key is 32 letters and digits, and is shown once, when it is made. Copy it then. The site keeps only a hash.
- Make a new key or Revoke the key disconnects a running server at once.
- Changing the game to
relaymode deletes its key. Going back to a server mode needs a new one. - Keep the key out of your source code and repositories. Read it from the environment or a file.
Connecting
| Address | play.commodoreonline.com, port 6503 |
| Transport | TLS 1.2 or later, with the site's certificate |
| Framing | One JSON object per line, ending in LF (a CR before it is ignored). At most 64 KB a line from the server |
| Text | UTF-8. Unknown fields in an op are refused (bad_request), so a typo shows at once |
| Who speaks first | The server, with hello, within 10 seconds of connecting, the TLS handshake included |
| Keep-alive | None needed. The hub never closes an idle server connection |
S> {"op":"hello","v":1,"game":"GUESS","key":"7K3M..."}
H> {"ev":"welcome","game":"GUESS","v":1}
The game id and key may be in any case. If the login fails, the hub sends an
error and closes the connection:
{"ev":"error","error":"bad_key","text":"wrong server key"}. These errors are
fatal, and reconnecting won't help: version, unknown_game,
no_server_mode, suspended, bad_key. Bad keys and unknown games count
against your address as players' bad tokens do: 10 in 10 minutes refuse its
logins for a while (busy).
After welcome, the hub sends forget for any deleted players you haven't
forgotten yet, in pages of 100, then open for every match and world
instance running, with a join for each player in it.
The hub disconnects the server at once if the game is suspended
(suspended), deleted (unknown_game), changed to relay mode
(no_server_mode), or its key changed (bad_key), and when the hub shuts
down (shutting_down).
Requests and replies
Any op may carry an id, a positive whole number. The hub then answers with
a reply once the op is done, after the events it caused:
S> {"op":"score","player":7,"board":"TRIES","value":5,"id":12}
H> {"ev":"reply","id":12,"ok":true,"board":"TRIES","rank":3,"value":5}
S> {"op":"score","player":7,"board":"NOPE","value":5,"id":13}
H> {"ev":"reply","id":13,"ok":false,"error":"no_board","text":"no such leaderboard, or not one a server submits to"}
Without an id, success is silent and a failure is an error event naming
the op, and the match if it had one:
{"ev":"error","op":"send","match":4,"error":"doesnt_fit","text":"seat 2: TOO MANY FIELDS"}.
kv_get is useless without one.
Payloads, text and data
Three kinds of content travel, each in its own field:
| Field | What | Encoding in JSON |
|---|---|---|
line |
A payload: what a player sends after ALL,, TELL,n, or TURN,, and what players get after FROM,0,. Byte for byte, with no character set conversion: PETSCII stays PETSCII |
A string with one character per byte, U+0000 to U+00FF. Plain ASCII is itself; the byte $C1 is the character U+00C1, Á |
text |
Free text: chat, and what the server writes for players to read | A normal Unicode string. The hub converts it to each player's character set |
data |
A binary frame's data, 0-127 bytes | Base64 |
Saved values (kv_get, kv_put) are bytes too, in base64.
Server to hub
op |
Fields | Reply | Meaning |
|---|---|---|---|
hello |
v (1), game, key |
welcome, or a fatal error |
Log in |
send |
match, to or place, and one of line, text (with wrap) or data |
sent: how many players got it |
Send to players in a match or world |
place |
match, seat, place, [quiet] |
Worlds: move a player to a place | |
start |
players, [match] |
match |
Form a match or party from players idle in the lobby, or admit them into a running world |
next |
match, seat |
Turn-based, after GO: it is now that seat's turn. Players get NEXT, and the turn's clock starts again. Without it, turns go round in seat order. Works on a stored match nobody is in |
|
end |
match, result, [reason] |
End the match and record the result: the winning seat, 0 for a draw, -1 for none. Players get OVER,<result>,"<reason>"; the reason defaults to <HANDLE> WINS, DRAW or NO RESULT. It counts for the wins board. Works on a stored turn-based match nobody is in |
|
kick |
match, seat, [reason] |
Remove a player. In a live match the seat is gone (the player gets OVER,-1,"<reason>", the others GONE). In a turn-based match after GO, the seat forfeits. In a world, the player is back in the lobby; a party member may RESUME. The default reason is REMOVED BY THE GAME |
|
score |
player, board, value |
board, rank, value (the kept value) |
Submit a score, 0-999,999,999, for a player by id. Any board but the wins board, including boards only the server may submit to |
kv_get |
scope, key |
value: base64, or null if not set |
Read saved data |
kv_put |
scope, key, value |
Save data: base64, up to 16 KB. An empty value deletes the key | |
forgot |
player |
You have deleted what you held about a deleted player (see forget) |
|
award |
player, achievement, title, [text] |
new: false if the player held it already |
Give a player an achievement (below) |
page |
text, [notices] |
Publish the game's page on the website, and its notices (below). "" removes it |
send's to: "all" (every player connected in the match), a seat
number, or a list of seats. A seat whose player is dropped or away is skipped
silently. A seat that isn't in the match, or has left for good, is no_seat.
In a world, send may have place instead of to: the players in that
place. In a world, only players who have sent READY get anything.
send with line: players get FROM,0,<line>, as they get each other's
messages. The line may not hold CR, LF or $00, and must fit every receiver:
their line limit with their padding, their field count, and whole quotes (see
payloads). If any receiver can't take it, nobody
gets it (doesnt_fit).
send with text: up to 1 KB of UTF-8, written as paragraphs. For each
receiver the hub:
- replaces
"with', and control codes with?; - converts it to the receiver's character set (an uppercase client gets uppercase);
- starts a new line at each newline; two newlines make a blank line, and one newline at the very end is dropped;
- wraps each paragraph at spaces to the receiver's width, cutting a word longer than a line;
- sends each line as
FROM,0,"<line>".
The width is one column less than the screen (on a Commodore, a full-width line followed by a return leaves a blank line), and no more than fits the line limit:
| Client | Columns |
|---|---|
VIC-20 (N) |
21 |
| C64 (40 columns) | 39 |
80 columns (W), with the default 6 fields |
67 |
| 80 columns, no padding | 70 |
80 columns with X (lines to 160 bytes) |
79 |
With "wrap": false the text is only split at newlines, spaces are kept, and
a line too long is cut: for maps and other preformatted text.
send with data: a binary frame from seat 0. Every receiver must have
flag B, or nobody gets it (no_binary).
Scopes for saved data: "game" is the game's own data; "player:<id>" is
a player's, the same values the player reads and writes with GET and PUT.
A player's values are 64 KB in all, and the game's 4 MB, the players'
included. Keys are 1-8 of A-Z and 0-9. Data that keeps growing, or needs
queries, belongs in your own storage.
Hub to server
ev |
Fields | Meaning |
|---|---|---|
welcome |
game, v |
Logged in |
open |
match, kind, playing, seats, [turn, resume, new] |
A match or world instance for you to run: it began, you have just logged in, or a stored match or party was read again. kind is live or turns, or for a world shared or party. seats is the roster, [{"seat","player","handle"}], with "out": true for a seat gone for good. playing: GO was sent already (always true in a world). turn: whose turn it is, 0 before GO. resume: a party that existed before; reload what you saved for it. new: a turn-based match started from the website (friends invited on the game's page), which you haven't been told of before. It started with nobody connected, so there was no ready: set up now what you would at GO, and next the seat to move if it isn't seat 1. It comes on the first open while you are connected; if the hub couldn't record that, a later open may carry it again, so set up only what isn't set up yet. A join follows for each player connected |
join |
match, seat, player, handle, cols, [place] |
A player is in the match: at its start, coming back with RESUME, or after open again. In a world: the player has sent READY, and place is where they are ("" until placed). player is the permanent id. cols is the screen width: 22, 40 or 80 |
ready |
match |
Every player sent READY: GO. Not sent for a match opened with playing, nor in a world |
msg |
match, seat, to, line or data |
A player's ALL (to is "all"), TELL,n (to is n; 0 is the server) or binary frame (to is the seat, or "all" for $FF). In observe mode, a copy of what was relayed |
turn |
match, seat, line, move |
A player's TURN, stored as move number move. In authority mode the others got only NEXT |
say |
match, seat, text |
Chat in the match or world |
drop |
match, seat |
The player's connection was lost; the seat is kept for the grace period |
back |
match, seat, cols |
The player is connected again, perhaps on another screen |
leave |
match, seat, out |
The seat left. out: true: for good. out: false: a turn-based player or a party member stepped away, and may RESUME (another join) |
end |
match, result |
Every player still in sent END: the result they agree on, or -1 if they disagree. Answer with end within 60 seconds, or the match ends with OVER,-1,"NO RESULT" |
close |
match, result, reason |
The match or world instance ended, for any reason. A seat still in it gets no leave |
forget |
player |
An account was deleted: delete what you keep about this player in your own storage, then send forgot. The hub has already deleted the player's saved data. It asks again at each login until you answer |
reply |
id, ok, ... |
The answer to an op that carried an id |
error |
error, text, [op, match] |
An op without an id failed; or, without op, the connection is about to close |
Every event about one match comes in the order it happened. A turn-based match or party nobody is in sends nothing; when someone comes back, it opens again.
Worlds
A world game's registration offers a shared world (one for everyone),
party instances (a group's own copy, saved between sessions), or both.
Its arrivals (presence) are announced by the hub (players get ENTER
and EXIT in their place) or by the server (you narrate them). The hub
keeps the seats, where each player is, and who hears what. Your server runs
everything else: rooms, exits, items, inventories, puzzles.
| Shared world | Party instance | |
|---|---|---|
| How players get in | A game with only a shared world puts them in it straight after HELLO; a game with both, with WORLD from the lobby; or your start with match |
Formed in the lobby like a match, or by your start. Later, any member's RESUME |
| Seats | Per visit: the lowest free one, up to the game's maximum | The members, fixed when it forms: at most 16 |
| Stored | No. When the last player has gone it stays open a minute, then closes (close, reason EMPTY). The next to enter opens a new one, with a new id, so key the world's state by game, not by id |
Yes. When nobody is in it, it waits; open with resume when a member comes back |
leave |
out: true |
out: false: the member may RESUME. out: true when a member leaves it for good |
Your end |
Everyone gets OVER; nothing is recorded |
Closed for good, and the result recorded |
| Ends by itself | When empty | After 90 days nobody has entered it (NOT VISITED), or when its last member leaves it for good (EVERYONE LEFT) |
- Entering. Each player gets
START, sendsREADYwhen their program is loaded, and getsGOat once; only then do you getjoin. There is noreadyevent in a world. placemoves a player who has sentREADYto a place: any name of 1-32 bytes of UTF-8, without control codes. With hub arrivals, and unless the move isquiet, those left behind getEXIT, those at the new placeENTER, and the player anENTERfor each player already there. A quiet move is unseen: the player isn't announced, isn't listed to later arrivals or byWHO, and isn't seen leaving, until moved again withoutquiet. Use it for a dark room, or a player following another. With server arrivals,sendto the place to narrate.- What players see.
SAYreaches the players in the speaker's place, and you hear it (say). Everything you send arrives asFROM,0, so players can always tell a player's voice from the game's. starttakesplayers, a list of player ids from earlierjoins, who must be logged in to the game and idle in its lobby. Withoutmatchit forms a match, or in a world game a party, in that seat order, and replies with its id after theopen. Withmatchit admits them into a running world: the shared world (fullif there isn't room), or a party they all belong to.- Parties are capped at 20 open per player and game; a new one past that
is refused (
too_manyto yourstart).
A shared world with hub arrivals, as it looks on the wire:
C> HELLO,1,CAVE,K7Q2M9XP,M
C< OK,ALICE
C< START,12,3,0,0
H> {"ev":"open","match":12,"kind":"shared","playing":true,"seats":[]}
C> READY
C< GO
H> {"ev":"join","match":12,"seat":3,"player":7,"handle":"ALICE","cols":40,"place":""}
S> {"op":"place","match":12,"seat":3,"place":"TAVERN"}
C< ENTER,5,BOB (Bob is there already)
S> {"op":"send","match":12,"to":3,"text":"You are in the tavern. Exits: north."}
C< FROM,0,"YOU ARE IN THE TAVERN. EXITS: NORTH."
C> SAY,"HI BOB"
H> {"ev":"say","match":12,"seat":3,"text":"hi bob"}
Achievements and the game's page
Two things a server publishes for the website, never for a Commodore. The My
Games page shows a player's achievements. A game's page shows its
achievements and the text its server publishes with page.
award gives a player an achievement:
| Field | Value |
|---|---|
player |
The player's permanent id, from join. The player must have played the game; otherwise no_player |
achievement |
The game's own name for it: 1-32 of a-z, 0-9 and -, not starting with -, such as first-try. Kept in lowercase |
title |
1-40 characters, such as First Try |
text |
Optional: a sentence of up to 120 characters |
S> {"op":"award","player":7,"achievement":"first-try","title":"First Try","text":"Guessed the number with the first guess.","id":5}
H> {"ev":"reply","id":5,"ok":true,"new":true}
S> {"op":"send","match":12,"to":1,"text":"Achievement: First Try!"}
- The hub tells the player nothing. Say it yourself, with
send, when the reply'snewis true. An award can come while the player isn't connected. newis false if the player held it already. That is no error, and the player keeps the time they first earned it.- The title and text become the achievement's for every holder, so awarding it again, to anyone, fixes a typo.
- Title and text are plain Unicode on one line, with no control or format characters, and must show something visible.
- A game has at most 200 achievements (
too_many).
page replaces the game's page with text: plain text, up to 4 KB of
UTF-8. Paragraphs are separated by a blank line; a single newline breaks a
line within a paragraph. There is no markup: the site shows the text as it
is, and doesn't make links of addresses. "" removes the page. The page
changes at most once a minute, after three at once (slow_down): it is
for plaques, milestones and news, not a live ticker.
A page may also carry notices: your game's fine print (terms, a privacy
notice, disclaimers), with the same rules and its own 4 KB. The game's page
shows them under "Notices", apart from the page and the description, unless
you have written notices on the game's settings page, which are shown
instead: there you can change them without a new server. Addresses on
commodoreonline.com become links there. Each page replaces both, so leave
notices out and they go.
S> {"op":"page","text":"Plaques in the cottage:\n\nTHE BLACK RIVER. FIRST REACHED BY ALICE.\nTHE MAZE. FIRST REACHED BY BOB.","id":6}
H> {"ev":"reply","id":6,"ok":true}
When the server is away
| While the server is away | When it comes back | |
|---|---|---|
| Players | NOTE,"THE GAME SERVER IS AWAY". Messages for the server, and everything in authority mode, get ERR,51 |
NOTE,"THE GAME SERVER IS BACK" |
| New matches | An authority game refuses MATCH, HOST and INVITE with ERR,51. An observe game plays on |
|
| Live matches | Authority: they wait 5 minutes, then end with OVER,-1,"NO GAME SERVER". Observe: they go on, relayed |
open and a join for each player; drop for those whose connection is lost |
| Turn-based matches | They wait, as they do for players. In authority mode TURN gets ERR,51, and turn limits keep running |
open when someone resumes or plays |
| Worlds | Players stay, and may still enter; after 5 minutes they hear the server is still away. Forming a party gets ERR,51 |
open and a join for each player, with their place |
Players' END |
The match ends with no result |
What a server misses while away is gone. The hub keeps no events for a
server that isn't connected. In an observe turn-based match, players go on
taking turns while the server is away, and open doesn't carry the history.
A server that must check every move should notice a gap in move numbers, or
the game should use authority mode, where TURN waits for the server.
Limits
| Limit | Value | Over it |
|---|---|---|
| A line from the server | 64 KB | too_long, and the connection closes |
text in one send |
1 KB, and at most 100 lines for a receiver | too_long |
A line in a send |
152 bytes | too_long |
| A saved value | 16 KB; 64 KB per player, 4 MB per game | too_long, data_full |
| Lines | 200 a second, bursting to 400 | Dropped: an op with an id gets slow_down; of the others, one error per burst |
Ops that touch storage (score, kv_get, kv_put, forgot, award, page, next, end, kick, start) |
50 a second, bursting to 200, besides the above | As above |
| Ops on matches and worlds not yet answered | 64 | slow_down |
| Stored matches and parties read at once | 16 per game | slow_down |
| A place's name | 1-32 bytes | bad_request |
start's players |
1-254 | bad_request |
| Achievements | 200 per game; an id of 1-32 characters, a title of 1-40, a text up to 120 | too_many, bad_request |
| The game's page | 4 KB; changed once a minute, after 3 at once | too_long, slow_down |
| Waiting to be sent to the server | 1 MB | The server isn't reading: disconnected |
Errors
| Code | Meaning |
|---|---|
bad_request |
Bad JSON, an unknown field, a value missing or out of range |
unknown_op |
No such op |
not_logged_in |
An op before hello (fatal) |
version |
The protocol version isn't 1 (fatal) |
unknown_game |
No such game, or deleted (fatal) |
no_server_mode |
The game is in relay mode (fatal) |
suspended |
The game is suspended (fatal) |
bad_key |
Wrong key, or the key was changed (fatal) |
replaced |
Another connection logged in with the key (fatal) |
shutting_down |
The hub is stopping: reconnect later |
not_now |
Not allowed now: hello twice, next on a live match or a world, an op on a turn-based match that is over, place on a match or on a player not READY, start with a player who isn't idle in the lobby |
no_match |
No such match of this game, a live match that has ended, or a party that is closed |
no_seat |
No such seat, or it has left for good |
doesnt_fit |
A line too long, or with too many fields or a stray quote, for a receiver |
no_binary |
A receiver of data can't take frames |
too_long |
A line, text, value or page over its limit |
no_player |
No such player, or the account was deleted; start: a player not logged in to the game; award: a player who never played the game |
no_board |
No such leaderboard, or the wins board |
data_full |
Saved data over its limits |
slow_down |
Over a rate limit, or too many ops on matches under way |
busy |
Storage can't be reached just now: try again. Also too many connections or failed logins |
full |
start: the shared world hasn't room for the players |
too_many |
start: a player belongs to 20 open parties of the game already; award: the game has 200 achievements already |
busy means nothing happened. When end, kv_put or another op that
waits for storage fails with busy, the match goes on and the value isn't
saved. A server that must not lose them tries again a few seconds later, and
stops when the match is gone (no_match).
Example: a guessing game in authority mode
The SDKs' guess example on the wire, with one player on a C64:
S> {"op":"hello","v":1,"game":"GUESS","key":"..."}
H> {"ev":"welcome","game":"GUESS","v":1}
C> MATCH,1 (and READY after START)
H> {"ev":"open","match":12,"kind":"live","playing":false,"seats":[{"seat":1,"player":7,"handle":"AL"}]}
H> {"ev":"join","match":12,"seat":1,"player":7,"handle":"AL","cols":40}
H> {"ev":"ready","match":12}
S> {"op":"send","match":12,"to":"all","text":"I'm thinking of a number from 1 to 100. Send me your guesses, and the first to find it wins."}
C< FROM,0,"I'M THINKING OF A NUMBER FROM 1 TO 100."
C< FROM,0,"SEND ME YOUR GUESSES, AND THE FIRST TO"
C< FROM,0,"FIND IT WINS."
C> TELL,0,60
H> {"ev":"msg","match":12,"seat":1,"to":0,"line":"60"}
S> {"op":"score","player":7,"board":"TRIES","value":1,"id":1}
H> {"ev":"reply","id":1,"ok":true,"board":"TRIES","rank":4,"value":1}
S> {"op":"end","match":12,"result":1,"reason":"AL GUESSED IT"}
C< OVER,1,"AL GUESSED IT"
H> {"ev":"close","match":12,"result":1,"reason":"AL GUESSED IT"}
The SDKs
Three SDKs wrap the protocol: Go, Python and C++. Each is a zip on the downloads page. Each has the same handlers and calls under its language's names, and the same examples.
| SDK | Needs | Form |
|---|---|---|
| Go | Go's standard library only | One module, retroswitch.com/gamehub (package gamehub) |
| Python | Python 3.10 or later, standard library only (asyncio, ssl, json) |
One package, retroswitch-gamehub: from retroswitch import gamehub |
| C++ | C++17, the system's sockets, and OpenSSL for TLS (or a transport of your own) | One header, <retroswitch/gamehub.h> (namespace retroswitch::gamehub) |
| Example | What it shows |
|---|---|
guess |
A number-guessing game in authority mode: text wrapped for each screen, end, score, a player's saved data, an achievement, a timer |
rooms |
A shared world of three rooms: place, text to a place, saved data per player, and a join after a restart that says where the hub has the player |
mill (Go) |
A cooperative text adventure for the text client, with party instances and arrivals narrated by the server |
What every SDK does
- One at a time. Handlers and timers run one at a time, in the order things happened, so a game needs no locks.
- Reconnecting. A lost connection is made again by itself: after 1
second, doubling to 30, and back to 1 after any connection that got as far
as
welcome. The hub then sendsopenandjoinagain for what is running. Only a fatal error (a bad key, an unknown or suspended game, another connection with the key) ends the run. - Backpressure. A write waits while the connection is full, for at most 10 seconds; then the connection is dropped and made again.
- Calls that wait.
next,end,kick,start,score,get,put,awardand the page wait for the hub's reply and return its error. The sends andplacedon't wait; their failures go to an error handler. forget. The handler deletes what you keep about a deleted player. When it succeeds the SDK answersforgot; if it fails, the hub asks again at the next login.
Handlers and calls
| Go | Python | C++ | When, or what |
|---|---|---|---|
Connected |
on_connected |
connected |
Logged in, again after a reconnect |
Disconnected |
on_disconnected |
disconnected |
The connection was lost |
Open |
on_open |
open |
A match or world instance to run |
Join |
on_join |
join |
A player is in a match, or has sent READY in a world |
Ready |
on_ready |
ready |
Every player sent READY (not in worlds) |
Msg |
on_msg |
msg |
A player's ALL, TELL or frame |
Turn |
on_turn |
turn |
A player's TURN, stored |
Say |
on_say |
say |
Chat |
Drop, Back, Leave |
on_drop, on_back, on_leave |
drop, back, leave |
A seat lost, back, or gone |
End |
on_end |
end |
The players reported a result |
Close |
on_close |
close |
A match or world instance ended |
Forget |
on_forget |
forget |
An account was deleted |
Error |
on_error |
error |
A send or place failed |
Send, SendText, SendPre, SendData |
send, send_text, send_pre, send_data |
send, send_text, send_pre, send_data |
send with a line, text, text with wrap: false, or data |
Place, PlaceQuiet |
place, place_quiet |
place, place_quiet |
place |
Next, End, Kick |
next, end, kick |
next, end, kick |
The match ops |
Start, Admit |
start, admit |
start, admit |
start without and with match |
Score |
score |
score |
score |
Get, Put |
get, put |
get, put |
kv_get, kv_put |
Award, SetPage, SetPageWithNotices |
award, set_page (with notices=) |
award, set_page (with notices as a second argument) |
award, page |
Request |
request |
request |
Any op, for ones the calls don't cover |
After, Every |
after, every |
after, every |
Timers |
to is "all", a seat, a list of seats, or a place in a world: gamehub.All,
gamehub.Seats(1, 2), gamehub.In("TAVERN") in Go; gamehub.ALL, 3,
gamehub.seats(1, 2), gamehub.In("TAVERN") in Python; gamehub::all, 3,
gamehub::seats(1, 2), gamehub::in("TAVERN") in C++. Scopes for saved data
are the game's (gamehub.Game, gamehub.GAME, gamehub::game_scope) and a
player's (PlayerScope(id), player_scope(id)).
Go
g := &Guess{}
err := gamehub.Run(ctx, gamehub.Config{
Addr: "play.commodoreonline.com:6503",
Game: "GUESS",
Key: os.Getenv("GUESS_KEY"),
}, g.Handlers())
A handler, from the guess example: a guess arrives as a payload, and the
answer goes back as text the hub wraps for the player's screen.
func (g *Guess) msg(s *gamehub.Server, e gamehub.Msg) {
m := g.matches[e.Match]
if m == nil || e.IsData {
return
}
n, err := strconv.Atoi(strings.TrimSpace(e.Line))
if err != nil || n < 1 || n > 100 {
s.SendText(e.Match, gamehub.Seats(e.Seat), "Send a number from 1 to 100.")
return
}
m.tries[e.Seat]++
switch {
case n < m.number:
s.SendText(e.Match, gamehub.Seats(e.Seat), fmt.Sprintf("%d is too low.", n))
case n > m.number:
s.SendText(e.Match, gamehub.Seats(e.Seat), fmt.Sprintf("%d is too high.", n))
default:
g.won(s, e.Match, m, e.Seat)
}
}
Python
Subclass gamehub.Handlers and override what the game needs. Each method may
be plain or async; every call is a coroutine.
import asyncio, os
from retroswitch import gamehub
class Echo(gamehub.Handlers):
async def on_msg(self, s: gamehub.Server, e: gamehub.Msg) -> None:
await s.send_text(e.match, e.seat, f"You said {e.line}.")
cfg = gamehub.Config(addr="play.commodoreonline.com:6503", game="ECHO",
key=os.environ["ECHO_KEY"])
asyncio.run(gamehub.run(cfg, Echo()))
Errors are exceptions: HubError (the hub's code, text, op, match
and fatal), NotConnected and NoReply, all gamehub.Error. Retrying an
end the hub was too busy for:
async def end_party(self, s, party):
try:
await s.end(party, gamehub.DRAW, "THE LEDGER IS FOUND")
except gamehub.HubError as e:
if e.code != "no_match":
s.after(5, lambda: self.end_party(s, party)) # until it holds
except gamehub.Error: # NotConnected, NoReply
s.after(5, lambda: self.end_party(s, party))
C++
#include <cstdio>
#include <cstdlib>
#include <retroswitch/gamehub.h>
namespace gamehub = retroswitch::gamehub;
int main() {
gamehub::Config cfg;
cfg.addr = "play.commodoreonline.com:6503";
cfg.game = "ECHO";
const char* key = std::getenv("ECHO_KEY");
cfg.key = key ? key : "";
gamehub::Handlers h;
h.msg = [](gamehub::Server& s, const gamehub::Msg& e) {
s.send_text(e.match, e.seat, "You said " + e.line + ".");
};
gamehub::Server server(cfg, h);
if( auto err = server.run() ) std::fprintf(stderr, "%s\n", err.message().c_str());
}
| Toolchain | Build (include: the SDK's include folder) |
|---|---|
| g++ or clang, Linux | g++ -std=c++17 -I include server.cpp -lssl -lcrypto -pthread |
| MSYS2 UCRT64 | g++ -std=c++17 -I include server.cpp -lssl -lcrypto -lws2_32 |
| MSVC without OpenSSL | cl /std:c++17 /EHsc /I include /DGAMEHUB_NO_OPENSSL server.cpp, with a TLS transport of your own in Config::transport |
Everything runs on the thread that calls run(). Other threads may only call
post(f), which runs f on that thread like a handler, and stop(). Calls
return an Error, empty on success, or a Result<T> with value and
error. On Windows, give OpenSSL its root certificates with
Config::ca_file.
Without an SDK
Any language with TLS and JSON will do: open a TLS connection to port 6503,
send hello, read one JSON object per line, and send ops. Use id on the
ops whose answers you need.
The development hub
The development hub, gamehub -dev, is the hub on your own computer
(Downloads; Getting
started says how to run it). Its
game servers' port is localhost:6503, with a self-signed certificate:
connect with the SDKs' insecure setting (Insecure, insecure), and with
any key. Register the game with the mode it needs, and start the server in a
second terminal:
gamehub -dev -game GUESS:1:4:LIVE:AUTHORITY
go run ./examples/guess -insecure # in the Go SDK's folder
python -m examples.guess --insecure # in the Python SDK's folder
For a transport without TLS, such as the C++ SDK built without OpenSSL,
-plainservers 127.0.0.1:6504 also takes servers without TLS on that
loopback address.
