Sling Academy
Home/Golang/Using WebSockets with Channels for Concurrent Communication in Go

Using WebSockets with Channels for Concurrent Communication in Go

Last updated: November 26, 2024

WebSockets provide a full-duplex communication channel that allows for real-time interaction between the client and the server. In the Go programming language, you can efficiently manage concurrent communications using channels. This article will guide you through setting up a WebSocket server using Go and handling concurrent messages using channels.

Setting Up a WebSocket Server

First, let's set up a basic WebSocket server using the popular gorilla/websocket package.

package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func main() {
    http.HandleFunc("/ws", handleConnections)
    log.Println("[1/3] Server started on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal(err)
    }
    defer ws.Close()

    for {
        var msg string
        err := ws.ReadJSON(&msg)
        if err != nil {
            log.Printf("[2/3] Error reading JSON: %v", err)
            break
        }
        fmt.Printf("[3/3] Received: %s\n", msg)
    }
}

This code sets up a WebSocket server that reads JSON-formatted messages from the client. It listens on port 8080 for incoming WebSocket connections.

Using Channels for Concurrent Communication

Go's channels provide a way to communicate safely between goroutines. When we incorporate them into our WebSocket implementation, we can manage multiple client connections concurrently.

type Client struct {
    conn *websocket.Conn
    send chan []byte
}

var clients = make(map[*Client]bool)
var broadcast = make(chan []byte)

In these definitions:

  • *Client represents each individual connection, holding a WebSocket connection and a send channel.
  • clients is a map that tracks all active client connections.
  • broadcast is a channel used to broadcast messages to all clients.

Next Article: Building a Real-Time Notifications System Using WebSockets in Go

Previous Article: Creating a Scalable WebSocket Backend with Goroutines in Go

Series: Websocket & Chat Programs in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant