5

[GopherJS] WebSocket Client Example With Echo Server

 2 years ago
source link: http://siongui.github.io/2017/05/18/go-websocket-client-example-with-echo-server/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[GopherJS] WebSocket Client Example With Echo Server

May 18, 2017

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:

[2]JavaScript Tips and Gotchas · gopherjs/gopherjs Wiki · GitHub

[4]A VPN-server, using websockets : golang

[5]peer to peer connection : golang

[6]Websocket Chat Rooms : golang


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK