Skip to content
tiennm99devPublic

About

Real-time Go game server — matchmaking, lobby chat, WebSocket + Protocol Buffers

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

mtplay

A real-time, turn-based game server in Go: lobby chat, Elo matchmaking and game sessions, using Protocol Buffers over WebSocket. Game rules plug in through a small interface.

Quick start

go run ./cmd/server          # listens on :8080
go test -race ./...          # run the test suite

A playable demo lives in template/: tic-tac-toe with a Phaser browser client, served by one Go binary. Copy it to start a new game.

Architecture

cmd/server/main.go              Entry point: picks the game and settings
internal/
  server/server.go              Wiring (lobby, matchmaker, sessions, /ws, /health, static files), HTTP serving, shutdown
  player/player.go              Player model and non-blocking outbound queue
  player/playertest/            In-memory connection for tests
  lobby/lobby.go                Room-based lobby with join/leave/chat broadcast
  matchmaking/matchmaker.go     Elo queue with expanding range
  game/session.go               Turn-based sessions and the Game rules interface
  game/rating.go                Elo rating update after each game
  game/nim/nim.go               Reference game (Nim), the current default
  ws/handler.go                 WebSocket upgrade, limits, message routing
  ws/rate_limit.go              Per-connection inbound rate limits
proto/game.proto                Protobuf schema (all message types)
pkg/pb/game.pb.go               Generated Go protobuf code

Protocol

All messages use binary protobuf over WebSocket. The Envelope message wraps every payload via a oneof:

Direction Message Purpose
C→S JoinLobbyRequest Join a lobby room (empty room id means default); sets your name
C→S LeaveLobbyRequest Leave current room
C→S ChatMessage Send chat to your room (1-500 characters)
C→S QueueRequest Enter matchmaking (its elo field is ignored)
C→S CancelQueueRequest Leave matchmaking queue
C→S GameAction Send a game action (your turn)
C→S ResignRequest Give up the current game, on any turn; the opponent wins
S→C Welcome First message: your server-assigned id, name and rating
S→C LobbyState Full room state on join
S→C PlayerJoined / PlayerLeft Room membership changes
S→C PlayerUpdated A room member's new info, such as the rating after a game; sent to the whole room
S→C ChatBroadcast Chat from a room member (including yourself)
S→C MatchFound Matched; players listed in turn order
S→C GameState Current game state + whose turn (current_turn is empty once the game has a result) and turn_time_left_ms, the time the player to move has (0 when turns have no limit)
S→C GameOver Winner (empty for a draw), reason, cause, and each player's new rating in scores. cause says what ended the game, and clients branch on it: END_CAUSE_RESULT (the game's rules decided it), END_CAUSE_FORFEIT, END_CAUSE_RESIGN, END_CAUSE_TIMEOUT and END_CAUSE_GAME_ERROR (the game's code failed; no winner, ratings unchanged). reason is display text only: the session sets opponent disconnected, player resigned, turn timed out or game error (game.Reason*) for its own causes, and a game's Result may return any text, these included
S→C Error Error response: 400 bad request, 403 not your turn or game over, 404 not in a game or not in a lobby room, 409 refused queue request (already in a game) or cancel after a match, 429 too many messages (the message was dropped; request_field is the dropped message's Envelope field number, such as 4 for queue, or 0 when the frame could not be decoded), 500 the game's code failed

A session always sends MatchFound before its first GameState, and GameState messages arrive in turn order. If a player disconnects during a game, the opponent wins by forfeit. Each move has a time limit (60 s by default): a player who does not move in time loses with turn timed out. GameOver is sent after the session has ended, so a client may queue again as soon as it arrives.

If the game's code panics (its factory, Apply, State or Result), only that session ends: its players get GameOver with cause END_CAUSE_GAME_ERROR, then Error 500, and the server keeps running. A game that fails before the match starts sends only the Error, and its players are not queued again.

Limits: frames over 16 KiB close the connection, names are capped at 32 characters, and a client that does not answer pings within 60 s, or falls 64 messages behind, is disconnected. Each connection may send 20 messages a second (bursts of 40), and of those 1 chat line a second (bursts of 5) and 1 room join every 2 seconds (bursts of 3), since chat lines and joins (which carry the player's name) reach the whole room; a message over a limit gets Error 429 naming it in request_field and is dropped, and the connection stays open. Every frame, malformed or not, counts against the 20-a-second limit before it is decoded. ws.Handler.SetRateLimits and SetJoinLimit change them. Open connections are capped at 1024 in all and 32 per client address (MAX_CONNS, MAX_CONNS_PER_IP); a connection over a cap is refused before the upgrade with HTTP 503 or 429. Behind a reverse proxy every client has the proxy's address, so set CLIENT_IP_HEADER to the header the proxy fills with the client's address, or all clients share one per-address cap.

Matchmaking

  • The server keeps each player's rating (starting at 1000) and updates it after every game (Elo, K=32). Ratings last for the connection.
  • Every 2 seconds the queue is scanned, longest-waiting player first.
  • Each player accepts opponents within ±100 Elo, widening by 50 per tick waited (max ±500). A pair matches when their difference is within the wider of the two ranges; the closest-rated opponent is picked.
  • The longest-waiting player of a pair moves first.

Game rules

A game implements game.Game (Apply, State, Result) and is passed to game.NewManager as a game.Factory. The session enforces turn order, the turn clock, resignation and game-over, and contains a panicking game; the game validates moves and decides the result. ws.NewHandler adds an OnGameOver hook, so after each game the players' rooms get PlayerUpdated with the new ratings; a game may add its own hooks (for example to save results) before or after, and every hook runs; a hook that panics is logged and the others still run. A game's command builds the server with server.New(server.Config{Game, TickInterval, TurnTimeout, AllowedOrigins, MaxConns, MaxConnsPerIP, ClientIPHeader, Static}), usually starting from server.EnvConfig(), which reads the variables below, and serves it with server.ListenAndServe; cmd/server and the template's command show both. The default is Nim (internal/game/nim): take 1-3 stones from a pile of 21 with a GameAction{action_type: "take", data: [n]}; whoever takes the last stone wins. GameState.state is JSON: {"pile":21,"lastBy":"1","lastTake":3}.

Configuration

Variable Default Purpose
ADDR :8080 Listen address
ALLOWED_ORIGINS empty Comma-separated browser origins (https://app.example.com) allowed besides same-origin pages
TURN_TIMEOUT 60s Time a player has for each move, as a Go duration (45s, 2m); a negative value means no limit
MAX_CONNS 1024 Most open WebSocket connections; a negative value means no cap
MAX_CONNS_PER_IP 32 Most open WebSocket connections from one client address; a negative value means no cap
CLIENT_IP_HEADER empty Header holding the client's address (such as X-Real-IP), for the per-address cap; for a list, the last entry is used. Set it only behind a reverse proxy that sets or overwrites the header, since a client connecting directly could spoof it

Run

ADDR=:9090 go run ./cmd/server

docker build -t mtplay .
docker run -p 8080:8080 mtplay

The root image runs the reference server (Nim, no web page). The playable tic-tac-toe game in template/ has its own image:

docker build -f template/Dockerfile -t mtplay-tictactoe .
docker run -p 8080:8080 mtplay-tictactoe   # http://localhost:8080

Generate Protobuf

Requires protoc-gen-go on PATH and buf (or go run):

go install google.golang.org/protobuf/cmd/protoc-gen-go
go run github.com/bufbuild/buf/cmd/buf@latest generate

Endpoints

GET /health → 200 "ok"
ws://localhost:8080/ws

About

Real-time Go game server — matchmaking, lobby chat, WebSocket + Protocol Buffers

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages