How to implement a WebSocket client for real-time communication in Go?

To implement a WebSocket client for real-time communication in Go, you can follow the steps below:

  1. Import the necessary packages:
import ( "log" "net/url" "os" "os/signal" "github.com/gorilla/websocket" )
  1. Create a websocket.Dialer instance:
var upgrader = websocket.Upgrader{} func main() { interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"} log.Println("Connecting to", u.String()) c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } defer c.Close()
  1. Implement a separate goroutine to read messages from the WebSocket connection:
go func() { defer c.Close() for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } log.Printf("received: %s\n", message) } }()
  1. Implement a goroutine to send messages to the WebSocket connection:
for { select { case <-interrupt: log.Println("interrupt") err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) if err != nil { log.Println("write close:", err) return } select { case <-done: case <-time.After(time.Second): } return } }
  1. Finally, in the main() function, handle any errors and run an infinite loop to keep the client running:
func main() { // ... previous code ... for { // ... previous code ... err = c.WriteMessage(websocket.TextMessage, []byte("Hello, server!")) if err != nil { log.Println("write:", err) return } // ... previous code ... } }

Make sure to replace the localhost:8080 in the u variable with the actual WebSocket server's address. Additionally, handle any errors appropriately based on your use case.

That's it! You now have a basic WebSocket client implemented in Go.