To implement a WebSocket client for real-time communication in Go, you can follow the steps below:
import (
"log"
"net/url"
"os"
"os/signal"
"github.com/gorilla/websocket"
)
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()
go func() {
defer c.Close()
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("received: %s\n", message)
}
}()
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
}
}
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.