Sling Academy
Home/Golang/Exploring Real-Time Collaborative Applications Using WebSockets in Go

Exploring Real-Time Collaborative Applications Using WebSockets in Go

Last updated: November 26, 2024

Developing real-time collaborative applications has become increasingly critical, especially with the rise of remote work and distributed teams. From code editors to interactive whiteboards, providing an instantaneous, seamless experience is essential. This article explores how to implement real-time collaboration using WebSockets in the Go programming language.

Understanding WebSockets

WebSockets is a protocol providing full-duplex communication channels over a single TCP connection. Unlike HTTP, it maintains an open connection, allowing servers to send data to clients without being explicitly requested.

Why Use WebSockets?

  • Bidirectional Communication: WebSockets allow real-time data transfer between the client and server.
  • Lower Latency: The continuous connection reduces the latency compared to regular HTTP requests.
  • Efficient: Uses fewer resources once the connection is established.

Setting Up a Basic WebSocket Server in Go

First, let’s set up a simple WebSocket server in Go. We’ll utilize the Gorilla Websocket library for our implementation.

package main

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

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

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

    for {
        var msg string
        err := ws.ReadJSON(&msg)
        if err != nil {
            fmt.Println("Error reading JSON:", err)
            break
        }
        fmt.Println("Received:", msg)
        response := "Echo: " + msg
        err = ws.WriteJSON(response)
        if err != nil {
            fmt.Println("Error writing JSON:", err)
        }
    }
}

func main() {
    http.HandleFunc("/ws", handleConnections)
    fmt.Println("Http server started on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("ListenAndServe Error:", err)
    }
}

This code sets up a basic WebSocket connection on localhost:8080. Once a client connects, the server will echo back any message it receives.

Client-Side Implementation

To test our WebSocket server, we'll create a simple HTML client.





    WebSocket Client


    
        let ws = new WebSocket('ws://localhost:8080/ws');

        ws.onopen = function() {
            console.log('Connected to server');
            ws.send('Hello Server');
        };

        ws.onmessage = function(event) {
            console.log('Received message:', event.data);
        };
    


Open this HTML file in your browser, and you should see the console logging messages confirming the connection and message exchanges with the server.

Enhancing the Application for Collaboration

By now, you have a simple WebSocket echo server and client. To extend it into a real-time collaborative application, you'll need to implement logic for handling multiple clients and broadcasting messages. A proper implementation will maintain a list of clients and push changes to all connected parties.

This is a fundamental framework for building real-time applications, and from here, you can progress towards more complex systems involving rooms or channels, user authentication, and conflict resolution.

Previous Article: Best Practices for Scaling WebSocket Servers 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