Skip to content

Ping Behavior Clarification #226

Closed
Closed
@JoshStrobl

Description

@JoshStrobl

Hey there,

I'm currently having some issues understanding what the expected implementation is for handling pings and pongs in a repeated fashion, primarily being used as a "heartbeat" indicator so I can free specific connections so I'm not sending data to socket connections which aren't active. I read over #186 and took a look at both of the examples in the repo and am trying to determine a few things:

I'm using wsjson.Read to read in requested data, as opposed to using the Reader / Read functions. This data is a JSON marshalled form of the struct listed below:

type WebSocketEvent struct {
	IDs  SocketKeys `json:"ids"`
	Type string     `json:"type"`
}

This is being read in as follows:

var request WebSocketEvent
if readErr := wsjson.Read(r.Context(), socketConn, &request); readErr != nil { // Read contents
	return
}

The type has a value, whether that's "init", "register", or "unregister". During "init", we'll perform some mapping and then call a go routine called Ping, providing the pointer the websocket.Conn. The desired implementation is basically to ping every 30 seconds or so and then after a few failures it'll unlisted it.

Is the pong response supposed to be automatically handled by the call to the connection's Ping function? Is this something that would be in the response handler (e.g. func SocketHandler(w http.ResponseWriter, r *http.Request)) instead? Or am I just missing something or going about it the wrong way.

Here's something I was testing, not actually functional but should give some idea on the context:

func Ping(c *websocket.Conn) {
	for {
		ctx, _ := context.WithTimeout(context.Background(), time.Second*15)
		trunk.LogInfo("Pinging client")

		pingErr := c.Ping(ctx)

		if pingErr == nil {
			trunk.LogSuccess("Pinged client")
			time.Sleep(time.Second * 30)
		} else {
			trunk.LogErr("Failed to ping client")
			RemoveConn(socketConn, "all", "all")
			return
		}
	}
}

Thanks in advance for your help!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions