To create a WebSocket server for bidirectional communication in Go, you can use the Gorilla WebSocket package. Here are the steps:
go get github.com/gorilla/websocket
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
// Upgrade HTTP connection to WebSocket connection
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Failed to upgrade connection:", err)
return
}
// Loop to handle incoming and outgoing messages
for {
// Read message from WebSocket client
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println("Failed to read message:", err)
break
}
// Print received message
log.Println("Received message:", string(p))
// Write message back to WebSocket client
err = conn.WriteMessage(messageType, p)
if err != nil {
log.Println("Failed to write message:", err)
break
}
}
}
func main() {
// Register WebSocket handler
http.HandleFunc("/ws", wsHandler)
// Start HTTP server
log.Println("Starting WebSocket server on port 8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
You can now connect WebSocket clients to ws://localhost:8080/ws
and send/receive messages to/from the server.