Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a golang.org/x/net/websocket open?

Tags:

websocket

go

I'm naively use _, err := ws.Read(msg) to keep a Web socket open in my code. I don't think it works reliably.

In other code I've noticed people doing a sleep loop. What's the correct way to keep a Web socket open & stable? I assume the underlying library does ping/pongs?

Update: I'm pretty confident that the client.go is to blame since it doesn't seem to redial after a disconnect is seen on the server. I made a video demonstrating the issue.

like image 362
hendry Avatar asked Jan 04 '16 12:01

hendry


2 Answers

golang.org/x/net/websocket does not implement ping-pong from RFC 6455, but the gorilla websocket implementation does. Minimal example with Gorilla websocket

c := time.Tick(pingInterval)
go func(){
       for  _ := range c {
           if err := conn.WriteControl(Ping...); err != nil {
                 handle error 
            }
      }
   }()

          -----

conn.SetPongHandler(func(string) error { return conn.SetReadDeadline(time.Now().Add(pingInterval)) })
go func(){
      for {
           if _, _, err := conn.NextReader(); err != nil {
                handle error
           }
       }
    }()
like image 73
Uvelichitel Avatar answered Nov 06 '22 04:11

Uvelichitel


I misread your original question.

No you're doing it the right away. You basically need to block the handler from returning to keep the websocket connection alive. If you don't care about the message, just discard it and do nothing with it.

A common way people do it is to have a dedicated Read and Write goroutine, something like:

func fishHandler(ws *websocket.Conn) {
    id := ws.RemoteAddr().String() + "-" + ws.Request().RemoteAddr + "-" + ws.Request().UserAgent()
    sockets[id] = ws

    go writePump(ws)
    readPump(ws)
}

func readPump(ws *websocket.Conn) {
    defer ws.Close()
    msg := make([]byte, 512)
    _, err := ws.Read(msg)
    if err != nil {
        return
    }
}

func writePump(ws *websocket.Conn) {
    // Hand the write messages here
}
like image 39
Datsik Avatar answered Nov 06 '22 04:11

Datsik