Skip to content

Commit

Permalink
Ping the websocket every 30 second disconencts are noticed. (#56)
Browse files Browse the repository at this point in the history
Sometimes socket are not closed neatly and the connection to a
(in-between) load balancer can be kept open. This pinging should trigger
the TCP protocol to disconnect.
  • Loading branch information
koenbollen authored Sep 7, 2023
1 parent a725db9 commit 4a4b93a
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
18 changes: 18 additions & 0 deletions internal/signaling/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ func Handler(ctx context.Context, store stores.Store, cloudflare *cloudflare.Cre
}
}()

go func() { // Sending ping packet every 30 to check if the tcp connection is still alive.
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := peer.Send(ctx, PingPacket{Type: "ping"}); err != nil {
util.ErrorAndDisconnect(ctx, conn, err)
}
case <-ctx.Done():
return
}
}
}()

for ctx.Err() == nil {
var raw []byte
if _, raw, err = conn.Read(ctx); err != nil {
Expand Down Expand Up @@ -109,6 +124,9 @@ func Handler(ctx context.Context, store stores.Store, cloudflare *cloudflare.Cre
}
go metrics.RecordEvent(ctx, params)

case "pong":
// ignore, ping/pong is just for the tcp keepalive.

default:
if err := peer.HandlePacket(ctx, typeOnly.Type, raw); err != nil {
util.ErrorAndDisconnect(ctx, conn, err)
Expand Down
4 changes: 4 additions & 0 deletions internal/signaling/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ import (
"github.com/poki/netlib/internal/signaling/stores"
)

type PingPacket struct {
Type string `json:"type"`
}

type HelloPacket struct {
Type string `json:"type"`

Expand Down
2 changes: 2 additions & 0 deletions lib/signaling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ export default class Signaling extends EventEmitter<SignalingListeners> {
case 'credentials':
this.emit('credentials', packet)
break
case 'ping':
break
}
} catch (e) {
const error = new SignalingError('unknown-error', e as string)
Expand Down
5 changes: 5 additions & 0 deletions lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,13 @@ export type SignalingPacketTypes =
| JoinPacket
| ListPacket
| LobbiesPacket
| PingPacket
| WelcomePacket

export interface PingPacket extends Base {
type: 'ping'
}

export interface ErrorPacket extends Base {
type: 'error'
message: string
Expand Down

0 comments on commit 4a4b93a

Please sign in to comment.