View : 0
12/04/2026 18:18pm

EP.44 Adding Active Users Feature in WebSocket Chat
#Online Users
#WebSocket
#Go
#Golang
#Real-Time Chat
#WebSocket API
#Active Users
#Chat Presence
#Chat UX
Why Have a Feature to Display the Number of Online Users?
The Active Users feature, which shows the number of users currently online, enhances the chat experience by allowing users to see who is available for interaction. This feature provides several benefits:
- Real-Time Interaction: Users can see which of their chat companions are online, making conversations more immediate and engaging.
- Dynamic User Count: It allows for the display of the number of active users in real-time.
- Ideal for Community or Support Chats: Facilitates quick responses in environments where timely communication is essential.
Structure of the Online User Count System in WebSocket Chat
- WebSocket Server: Monitors the online status of users and notifies others when changes occur.
- Database (Optional): Can be used to store user online status data for long-term tracking.
- Frontend (Client-Side): Displays the number of online users and updates in real-time.
Adding the Active Users Feature to the WebSocket Server
1. Upgrade the WebSocket Server to Support Online Status Tracking
File websocket_server.go
package main
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"github.com/gorilla/websocket"
)
type UserStatus struct {
Username string `json:"username"`
Online bool `json:"online"`
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
var (
clients = make(map[*websocket.Conn]string)
onlineUsers = make(map[string]bool)
broadcast = make(chan UserStatus)
mu sync.Mutex
)
func handleConnections(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil)
defer conn.Close()
var username string = r.URL.Query().Get("username")
mu.Lock()
clients[conn] = username
onlineUsers[username] = true
mu.Unlock()
broadcast <- UserStatus{Username: username, Online: true}
for {
_, _, err := conn.ReadMessage()
if err != nil {
mu.Lock()
delete(clients, conn)
delete(onlineUsers, username)
mu.Unlock()
broadcast <- UserStatus{Username: username, Online: false}
break
}
}
}
func handleMessages() {
for {
status := <-broadcast
fmt.Printf("User %s is now %s\n", status.Username, map[bool]string{true: "online", false: "offline"}[status.Online])
for client := range clients {
err := client.WriteJSON(status)
if err != nil {
client.Close()
mu.Lock()
delete(clients, client)
mu.Unlock()
}
}
}
}
func main() {
http.HandleFunc("/ws", handleConnections)
go handleMessages()
fmt.Println("WebSocket Server Running on Port 8080")
http.ListenAndServe(":8080", nil)
}2. Adding Active Users Functionality in the Frontend (Client-Side)
File client.js
const username = prompt("Enter your username:");
const socket = new WebSocket(`ws://localhost:8080/ws?username=${username}`);
const onlineUsersContainer = document.getElementById("online-users");
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
updateOnlineUsers(data.username, data.online);
};
function updateOnlineUsers(username, online) {
let userElement = document.getElementById(`user-${username}`);
if (!userElement) {
userElement = document.createElement("p");
userElement.id = `user-${username}`;
onlineUsersContainer.appendChild(userElement);
}
userElement.innerText = `${username} is ${online ? "Online" : "Offline"}`;
}Displaying Active Users on the UI
File index.html
<div id="online-users"></div>3. Testing the System
- Run the WebSocket Server
go run websocket_server.go- Open Multiple Browser Tabs and Log in with different usernames
- Observe Results at WebSocket Server and UI
Challenge!
Try adding a Last Seen feature to display when a user was last active. This will allow others to know when the user was last online, even if they are currently offline.
Next EP
In EP.45, we will add a Notification System for When New Users Join the WebSocket Chat! 🚀