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:
*Clientrepresents each individual connection, holding a WebSocket connection and a send channel.clientsis a map that tracks all active client connections.broadcastis a channel used to broadcast messages to all clients.