View : 0

12/04/2026 18:17pm

EP.92 Using WebSocket for Real-time Online Game Development

EP.92 Using WebSocket for Real-time Online Game Development

#Golang

#Real-time Game

#WebSocket Server

#WebSocket

Building a real-time online game requires more than just game logic — it demands fast, efficient, and low-latency communication between players and the server. WebSocket is an ideal protocol for enabling real-time, bidirectional communication in multiplayer games.

 

In this article, we’ll explore how to use WebSocket with Go (Golang) to develop scalable, real-time multiplayer games. You’ll learn best practices, common pitfalls, and example code to get started.

 

1. Managing Player State

 

In a multiplayer game, the server needs to track each player's state in real time — including position, health, status, and score.

 

Store player state in memory (e.g., in a map) or use Redis for distributed instances.

 

Example: Basic Player Struct in Go

type Player struct {
    ID     string  `json:"id"`
    X, Y   float64 `json:"x_y"`
    HP     int     `json:"hp"`
    Status string  `json:"status"`
}

The server can update and broadcast the player state using WebSocket to all clients in the same room.

 

2. Sending Position and Events in Real Time

 

Use WebSocket messages to continuously transmit player positions and important events.

  • Send delta updates only when the data has changed.
  • Use binary encoding (e.g., Protobuf or MessagePack) for smaller message sizes.

 

Example: WebSocket Position Broadcast

message := Player{
    ID: "player1",
    X: 123.45,
    Y: 67.89,
    HP: 100,
}
jsonData, _ := json.Marshal(message)
hub.BroadcastToRoom("room123", jsonData)

 

3. Reducing Latency with Prediction & Reconciliation

 

Latency is inevitable. But you can minimize its effects by:

  • Implementing client-side prediction so the player sees immediate feedback.
  • Using server reconciliation to correct incorrect positions.
  • Setting an appropriate tick rate (e.g., 30–60 updates per second) based on your game type.

 

4. Designing the Multiplayer Game Architecture

 

A scalable WebSocket-based multiplayer game must consider:

  • Room/Lobby System: Group players into logical sessions or game rooms.
  • Load Balancing: Use a load balancer in front of multiple WebSocket servers.
  • Message Protocol: Design event types like Move, Attack, Chat, Disconnect.

 

Example: Event Protocol (JSON Format)

{
  "type": "move",
  "playerId": "p1",
  "x": 12.5,
  "y": 4.3,
  "timestamp": 1699999999
}

 

5. Best Practices for WebSocket Game Servers

 

✅ Only send essential data — skip redundant info
✅ Use timestamps for event ordering and lag correction
✅ Compress messages or use binary formats
✅ Stress-test with load testing tools like k6, Artillery, or custom Go scripts
✅ Optimize tick rate based on device/network performance

 

Sample Go WebSocket Handler for a Game

 

func gameSocketHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("Upgrade error:", err)
        return
    }
    defer conn.Close()

    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            log.Println("Read error:", err)
            break
        }

        var event GameEvent
        if err := json.Unmarshal(msg, &event); err == nil {
            handleGameEvent(event)
            broadcastToRoom(event.RoomID, msg)
        }
    }
}

 


 

Final Thoughts

Using WebSocket to build real-time online games gives you the power to create fast, interactive, and engaging multiplayer experiences. With proper architecture, protocol design, and latency control, your game server can handle thousands of players with confidence.

 

🔥 Challenge Before Next Episode

 

🎯 Try building a simple WebSocket-based game:

  • Create a lobby
  • Allow multiple players to move on a shared canvas
  • Use k6 to test 100 concurrent connections
  • Track latency and update rates

Then analyze what can be improved in your architecture. Share your results with your team!

 

🔜 Next EP.93:

 

Adding Voice and Video Communication to Your WebSocket Chat System

Learn how to enhance your real-time communication by integrating audio/video features with WebRTC + WebSocket signaling.

 

Read more

🔵 Facebook: Superdev Academy

🔴 YouTube: Superdev Academy

📸 Instagram: Superdev Academy

🎬 TikTok: https://www.tiktok.com/@superdevacademy?lang=th-TH

🌐 Website: https://www.superdevacademy.com/en