[GopherJS] WebSocket Client Example With Echo Server


Simple example of a WebSocket client via GopherJS and Golang. Connect and send a message to the WebSocket server that echos everything from clients.

The WebSocket echo server is provided by websocket.org and the address is wss://echo.websocket.org.

Run Code on GopherJS Playground

package main

import (
      "fmt"

      "github.com/gopherjs/gopherjs/js"
)

func main() {
      ws := js.Global.Get("WebSocket").New("wss://echo.websocket.org")

      ws.Call("addEventListener", "open", func(e *js.Object) {
              fmt.Println("Connection open ...")
              ws.Call("send", "Hello WebSockets!")
      })

      ws.Call("addEventListener", "message", func(e *js.Object) {
              fmt.Println("Received Message: " + e.Get("data").String())
              ws.Call("close")
      })

      ws.Call("addEventListener", "close", func(e *js.Object) {
              fmt.Println("Connection closed.")
      })
}

Console output:

Connection open ...
Received Message: Hello WebSockets!
Connection closed.

References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]JavaScript Tips and Gotchas · gopherjs/gopherjs Wiki · GitHub
[3]
[4]A VPN-server, using websockets : golang
[5]peer to peer connection : golang
[6]Websocket Chat Rooms : golang