Real-time Communication with WebSockets
7 min read
Real-time Communication with WebSockets WebSocket WebSocket
Welcome to the thrilling world of real-time communication with Fiber! 🚀 In this guide, we'll unravel the magic of WebSockets and how they empower your applications to have instantaneous, two-way conversations.
Understanding WebSockets vs. HTTP
Let's start with the basics. Imagine you're at a restaurant.
HTTP is like a traditional waiter service. You (the client) have to call the waiter (make a request) every single time you want something. The waiter brings your order (the response), and then they leave. If you want another drink, you have to flag them down again. This is the request-response model that HTTP follows. It's reliable but can be inefficient if you need constant updates.
WebSockets, on the other hand, are like having a dedicated server at your table. Once you've established a connection (the initial handshake), that connection stays open. You and the server can talk to each other freely without having to go through the whole process of getting each other's attention every time. This is a full-duplex, persistent communication channel.
The Problem: Traditional web applications built solely on HTTP struggle with real-time features. Think about a live chat application. With HTTP, the client would have to constantly ask the server, "Are there any new messages?" This process, called polling, is resource-intensive and introduces delays.
The Solution: WebSockets! They provide a persistent, two-way communication channel over a single TCP connection, making them perfect for applications that require low-latency, real-time data exchange.
Here's a quick rundown of the key differences:
| Feature | HTTP | WebSockets |
|---|---|---|
| Communication | Unidirectional (client-initiated) | Bidirectional (client and server can both initiate) |
| Connection | A new connection is made for each request | A single, persistent connection |
| Overhead | Higher due to repeated headers for each request | Lower after the initial handshake |
| Real-time | Limited (requires polling) | Natively supported |
An Interesting Fact: The WebSocket protocol was standardized in 2011, and its creation was largely driven by the need for more interactive and real-time web applications, like live sports updates, online gaming, and collaborative editing tools.
Setting up the Fiber WebSocket Middleware
Now that we understand the "why," let's get our hands dirty with the "how." Setting up WebSockets in Fiber is surprisingly straightforward.
First things first, you'll need to have a Go environment set up and a new Fiber project initialized. If you haven't already, you can do so with these commands:
mkdir my-fiber-ws-app
cd my-fiber-ws-app
go mod init my-fiber-ws-appNext, you'll need to install the necessary Fiber packages:
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/contrib/websocketWith the dependencies in place, let's create a basic Fiber application and set up the WebSocket middleware. Create a main.go file with the following code:
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/websocket"
)
func main() {
app := fiber.New()
app.Use("/ws", func(c *fiber.Ctx) error {
// IsWebSocketUpgrade returns true if the client
// requested upgrade to the WebSocket protocol.
if websocket.IsWebSocketUpgrade(c) {
c.Locals("allowed", true)
return c.Next()
}
return fiber.ErrUpgradeRequired
})
app.Get("/ws", websocket.New(func(c *websocket.Conn) {
// c.Locals is added to the *websocket.Conn
log.Println(c.Locals("allowed")) // true
var (
mt int
msg []byte
err error
)
for {
if mt, msg, err = c.ReadMessage(); err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", msg)
if err = c.WriteMessage(mt, msg); err != nil {
log.Println("write:", err)
break
}
}
}))
log.Fatal(app.Listen(":3000"))
}Let's break down what's happening here:
app.Use("/ws", ...): This is a middleware that specifically targets requests to the/wspath.websocket.IsWebSocketUpgrade(c): This function checks if the incoming request is a WebSocket upgrade request. This is how the initial "handshake" happens, where an HTTP connection is upgraded to a WebSocket connection.app.Get("/ws", websocket.New(...)): This is where the magic happens. We're defining a WebSocket endpoint. Thewebsocket.Newfunction takes a handler function that will be executed for each new WebSocket connection.
To test this, you can use a simple JavaScript client in your browser's console:
const ws = new WebSocket('ws://localhost:3000/ws');
ws.onopen = () => {
console.log('connected');
ws.send('Hello, Server!');
};
ws.onmessage = (event) => {
console.log('from server:', event.data);
};Handling Client Connections and Messages
Once a client is connected, you'll want to be able to handle their messages and send them responses. In our previous example, the core of this logic is within the for loop:
for {
if mt, msg, err = c.ReadMessage(); err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", msg)
if err = c.WriteMessage(mt, msg); err != nil {
log.Println("write:", err)
break
}
}c.ReadMessage(): This is a blocking call that waits for a message to arrive from the client. It returns the message type, the message itself as a byte slice, and any error that occurred.c.WriteMessage(mt, msg): This function sends a message back to the client. It takes the message type and the message payload as arguments.
A crucial industry practice is to gracefully handle disconnections. The ReadMessage method will return an error when a client disconnects. It's important to detect this and clean up any resources associated with that client.
Building a Simple Chat Room Broadcaster
Now for the grand finale! Let's build a simple chat room where messages from one client are broadcast to all other connected clients. This is a classic use case for WebSockets.
We'll need a way to keep track of all the connected clients. A simple map will do the trick. We'll also use channels to safely manage concurrent access to our client list.
Here's the code for our chat room broadcaster:
package main
import (
"log"
"sync"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/contrib/websocket"
)
// A thread-safe map to store clients
type client struct{} // empty struct is used as we only need the key
var clients = make(map[*websocket.Conn]client)
var clientsMutex = sync.RWMutex{}
// Channel to broadcast messages to all clients
var broadcast = make(chan []byte)
func registerClient(c *websocket.Conn) {
clientsMutex.Lock()
clients[c] = client{}
clientsMutex.Unlock()
log.Println("client connected:", c.RemoteAddr())
}
func unregisterClient(c *websocket.Conn) {
clientsMutex.Lock()
delete(clients, c)
clientsMutex.Unlock()
log.Println("client disconnected:", c.RemoteAddr())
}
func handleMessages() {
for {
// Grab the next message from the broadcast channel
msg := <-broadcast
clientsMutex.RLock()
// Send it out to every client that is currently connected
for c := range clients {
if err := c.WriteMessage(websocket.TextMessage, msg); err != nil {
log.Println("write:", err)
// If there's an error, assume the client disconnected
// and remove them.
unregisterClient(c)
c.Close()
}
}
clientsMutex.RUnlock()
}
}
func main() {
app := fiber.New()
app.Use("/ws", func(c *fiber.Ctx) error {
if websocket.IsWebSocketUpgrade(c) {
return c.Next()
}
return fiber.ErrUpgradeRequired
})
// Run the message handler in a separate goroutine
go handleMessages()
app.Get("/ws", websocket.New(func(c *websocket.Conn) {
// When the function returns, unregister the client
defer unregisterClient(c)
registerClient(c)
for {
_, msg, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", msg)
// Send the message to the broadcast channel
broadcast <- msg
}
}))
log.Fatal(app.Listen(":3000"))
}In this more advanced example:
- We have a
clientsmap to store all active connections. - We use a
sync.RWMutexto protect ourclientsmap from concurrent access, which is a common issue in multi-goroutine applications. - The
broadcastchannel acts as a central hub for all incoming messages. - The
handleMessagesfunction runs in a separate goroutine and continuously listens for messages on thebroadcastchannel. When a message is received, it iterates through all connected clients and sends them the message. - Our WebSocket handler now registers a new client upon connection and sends any received messages to the
broadcastchannel.
Funny Exaggeration Time: Imagine trying to build this chat room with just HTTP. It would be like a town crier running to every single house individually to deliver each message. With WebSockets, you have a town square with a magical megaphone that instantly reaches everyone at once!
Extra Reading & References
Challenge
Challenge: Multi-Room WebSocket Broadcaster
Your task is to build a Go application using the Fiber framework that hosts a WebSocket server for a multi-room chat application. Clients should be able to connect to specific rooms via the URL, and messages sent by a client should only be broadcast to other clients in the same room.
Requirements:
- Set up a Fiber web server.
- Create a single WebSocket endpoint at the path
/ws/:room, where:roomis a dynamic path parameter representing the chat room name. - Implement a system to manage client connections on a per-room basis. Use a
mapwhere keys are room names and values are data structures holding the connections for that room. - The data structure managing rooms and connections must be safe for concurrent access. Use a
sync.RWMutexto protect it. - When a client connects, they should be added to the list of clients for the room specified in the URL.
- When a client disconnects, they must be cleanly removed from their room's client list.
- Implement a central broadcasting mechanism using a single Go channel. When a client sends a message, it should be passed to this channel.
- A separate, continuously running goroutine (
runHubin the initial code) must listen on the broadcast channel. When it receives a message, it should send that message to all other clients currently connected to the same room. The original sender should not receive their own message back.
Expected result
Your final code should be a complete, runnable Go program that correctly implements the multi-room WebSocket broadcaster.
Correct Implementation Checklist:
- Client Registration: When a client connects to
/ws/general, your code should safely add their connection to amapassociated with the"general"key inside the globalroomsstructure. - Disconnection Handling: The
deferblock correctly and safely removes the client's connection from theroomsmap when they disconnect. - Message Reading: The
forloop inside thewebsocket.Newhandler successfully reads incoming messages from the client. - Broadcasting Logic: For each message read, a
Messagestruct is created and sent to thebroadcastchannel. - Hub Logic: The
runHubfunction correctly receives messages from the channel and iterates through the connections for the appropriate room, writing the message content to every client except the one that sent it. - Concurrency Safety: All read and write operations on the shared
rooms.mmap are protected byrooms.Lock(),rooms.Unlock(),rooms.RLock(), androoms.RUnlock()to prevent race conditions.