From f33b3ba5ce5d1c660c2b2995609405fbb15775c8 Mon Sep 17 00:00:00 2001 From: Justin M <37273682+DigitalAlchemist@users.noreply.github.com> Date: Tue, 5 Jan 2021 05:40:44 +0000 Subject: [PATCH] Ping websocket to ensure connect remains online. OpenWebTorrent disconnects clients after two minutes of inactivity. In a scenario where an announce occurs and no other activity occurs for the (default) 120-second idle timer, the websocket will be torn down by OpenWebTorrent. This in turn causes the tracker client to wait one minute, reconnect, and reannounce its peers. This patch sends a websocket.PingMessage every 60 seconds to maintain the connection. --- webtorrent/tracker_client.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/webtorrent/tracker_client.go b/webtorrent/tracker_client.go index 47267e0e..c5aacaf2 100644 --- a/webtorrent/tracker_client.go +++ b/webtorrent/tracker_client.go @@ -35,6 +35,7 @@ type TrackerClient struct { wsConn *websocket.Conn closed bool stats TrackerClientStats + pingTicker *time.Ticker } func (me *TrackerClient) Stats() TrackerClientStats { @@ -78,7 +79,23 @@ func (tc *TrackerClient) doWebsocket() error { tc.cond.Broadcast() tc.mu.Unlock() tc.announceOffers() + closeChan := make(chan struct{}) + go func() { + for { + select { + case <-tc.pingTicker.C: + err := c.WriteMessage(websocket.PingMessage, []byte{}) + if err != nil { + return + } + case <-closeChan: + return + default: + } + } + }() err = tc.trackerReadLoop(tc.wsConn) + close(closeChan) tc.mu.Lock() c.Close() tc.mu.Unlock() @@ -86,6 +103,7 @@ func (tc *TrackerClient) doWebsocket() error { } func (tc *TrackerClient) Run() error { + tc.pingTicker = time.NewTicker(60 * time.Second) tc.cond.L = &tc.mu tc.mu.Lock() for !tc.closed { @@ -112,6 +130,7 @@ func (tc *TrackerClient) Close() error { tc.wsConn.Close() } tc.closeUnusedOffers() + tc.pingTicker.Stop() tc.mu.Unlock() tc.cond.Broadcast() return nil -- 2.44.0