Skip to content

Instantly share code, notes, and snippets.

/websocket.go Secret

Created Mar 19, 2018
Embed
What would you like to do?
package main
import (
"flag"
"log"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
var addr = "wss://api.radarrelay.com/0x/v0/ws"
func main() {
flag.Parse()
log.SetFlags(0)
timeoutDuration := 2 * time.Minute
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
c, _, err := websocket.DefaultDialer.Dial(addr, nil)
if err != nil {
log.Fatal("dial:", err)
} else {
log.Println("Connected to server")
}
c.SetPongHandler(func(str string) error {
log.Println("pong received", str)
return nil
})
defer c.Close()
done := make(chan struct{})
go func() {
defer c.Close()
defer close(done)
for {
c.SetReadDeadline(time.Now().Add(timeoutDuration))
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
if len(message) >= 2 {
message = message[2:]
}
log.Printf("recv: %s", message)
}
}()
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case _ = <-ticker.C:
err := c.WriteMessage(websocket.PingMessage, []byte{})
if err != nil {
log.Println("write:", err)
return
} else {
log.Println("ping sent")
}
case <-interrupt:
log.Println("interrupt")
// To cleanly close a connection, a client should send a close
// frame and wait for the server to close the connection.
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):
}
c.Close()
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.