How to Build Go WebSocket Server and Client for Inter-Service Communication

This guide demonstrates how to create a Go-based WebSocket server and client using the gobwas library, enabling two services to exchange random numbers, handle connections, and gracefully manage disconnections, with complete code examples and testing instructions.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Build Go WebSocket Server and Client for Inter-Service Communication

This article introduces how to implement WebSocket communication between two Go services, where one program acts as the server and the other as a client.

WebSocket Server

The server code is straightforward; we use the gobwas module to avoid reinventing the wheel.

Below is the code for a WebSocket server listening on port 8080.

package main

import (
    "fmt"
    "github.com/gobwas/ws"
    "github.com/gobwas/ws/wsutil"
    "math/rand"
    "net/http"
    "strconv"
)

func main() {
    fmt.Println("Server started, waiting for connection from client")
    http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Println("Client connected")
        conn, _, _, err := ws.UpgradeHTTP(r, w)
        if err != nil {
            fmt.Println("Error starting socket server: " + err.Error())
        }
        go func() {
            defer conn.Close()
            for {
                msg, op, err := wsutil.ReadClientData(conn)
                if err != nil {
                    fmt.Println("Error receiving data: " + err.Error())
                    fmt.Println("Client disconnected")
                    return
                }
                fmt.Println("Client message received with random number: " + string(msg))
                randomNumber := strconv.Itoa(rand.Intn(100))
                err = wsutil.WriteServerMessage(conn, op, []byte(randomNumber))
                if err != nil {
                    fmt.Println("Error sending data: " + err.Error())
                    fmt.Println("Client disconnected")
                    return
                }
                fmt.Println("Server message send with random number " + randomNumber)
            }
        }()
    })))
}

The server does nothing beyond waiting for connections; it prints received data and finally sends a random integer back. If the client disconnects, the server logs the disconnection.

WebSocket Client

The client code is similar and also uses the gobwas module.

The client connects to ws://127.0.0.1:8080/ on localhost.

package main

import (
    "context"
    "fmt"
    "github.com/gobwas/ws"
    "github.com/gobwas/ws/wsutil"
    "math/rand"
    "os"
    "strconv"
    "time"
)

func main() {
    fmt.Println("Client started")
    for {
        conn, _, _, err := ws.DefaultDialer.Dial(context.Background(), "ws://127.0.0.1:8080/")
        if err != nil {
            fmt.Println("Cannot connect: " + err.Error())
            time.Sleep(time.Duration(5) * time.Second)
            continue
        }
        fmt.Println("Connected to server")
        for i := 0; i < 10; i++ {
            randomNumber := strconv.Itoa(rand.Intn(100))
            msg := []byte(randomNumber)
            err = wsutil.WriteClientMessage(conn, ws.OpText, msg)
            if err != nil {
                fmt.Println("Cannot send: " + err.Error())
                continue
            }
            fmt.Println("Client message send with random number " + randomNumber)
            msg, _, err = wsutil.ReadServerData(conn)
            if err != nil {
                fmt.Println("Cannot receive data: " + err.Error())
                continue
            }
            fmt.Println("Server message received with random number: " + string(msg))
            time.Sleep(time.Duration(5) * time.Second)
        }
        err = conn.Close()
        if err != nil {
            fmt.Println("Cannot close the connection: " + err.Error())
            os.Exit(1)
        }
        fmt.Println("Disconnected from server")
    }
}

The client simply connects, sends random integers every 5 seconds, and prints any response from the server.

Test

Left: server result, Right: client result

The client sends a random number to the server every 5 seconds, and the server replies with another random number.

If you stop the server, the client will show that the server has disconnected; restarting the server causes the client to reconnect. Similarly, stopping the client makes the server log a disconnection, and running the client again reconnects it.

Since Go is frequently used for services and microservices, communication between such services is meaningful.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentGoWebSocketgobwasInter-Service Communication
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.