websocket icon indicating copy to clipboard operation
websocket copied to clipboard

Is it necessary to send ping messages by hand?

Open kuchaguangjie opened this issue 3 years ago • 4 comments
trafficstars

I've wrtten a websocket server in fiber's websocket, and the client is js websocket in browser.

Some questions regarding ping/pong:

  1. Is there any default ping/pong msg between the websocket server & client? If yes, then why I can't see it in chrome's devtools.
  2. If there isn't any defult ping/pong msg, should I add ping/pong between server & client myself?
  3. If it's a good practice to add ping/pong msg myself, then:
  4. Is it better to send ping from client to server, or reverse?
  5. Since conn.ReadJSON() will block, does that means I should use conn.SetPingHandler() to specify a handler, or JUST use the default handler? In either case, the ping need to be sent from client to server I guess.

kuchaguangjie avatar Jun 17 '22 05:06 kuchaguangjie

Also asked in stackoverflow: https://stackoverflow.com/q/72654705/1568658

kuchaguangjie avatar Jun 17 '22 05:06 kuchaguangjie

I added a testing ping sent from fiber websocket server to js client, if needed:


		// ping
		// TODO: not sure is this needed ?
		// TODO: use goroutine pool ?
		if needPing {
			go func() {
				pingTicker := time.NewTicker(pingPeriod)
				defer func() {
					pingTicker.Stop()
				}()
				time.Sleep(pingPeriod) // wait a while before start ping,
				for {
					select {
					case <-pingTicker.C:
						conn.WriteControl(websocket.PingMessage, []byte("ping"), time.Now().Add(time.Second*5))
						log.Debug("ping")
					}
				}
			}()
		}

I also don't see any ping msg on client in chrome's devtools.

It's better to use for{ select } to handle both ping & normal msg I guess, but conn.ReadJSON() would block the goroutine, might need to create a channel for it? Didn't try yet.

BTW, any suggestion to the ping impl?

kuchaguangjie avatar Jun 17 '22 05:06 kuchaguangjie

Is there any answer?

sedyh avatar Sep 30 '22 22:09 sedyh

@sedyh In my experience, seems no need ping, on client just use onclose handler, then it's enough, I think.

kuchaguangjie avatar Oct 01 '22 05:10 kuchaguangjie

how do we detect disconnection on server side so we can remove the socket?

daveteu avatar Nov 25 '22 01:11 daveteu

@daveteu Use Conn's SetCloseHandler().

kuchaguangjie avatar Nov 25 '22 03:11 kuchaguangjie

@kuchaguangjie thank u. I think this is useful if client sends close signals. If e.g I connect via curl, it doesn't trigger.

daveteu avatar Nov 30 '22 12:11 daveteu