diff --git a/internal/signaling/handler.go b/internal/signaling/handler.go index 3ac63aa..8a763bf 100644 --- a/internal/signaling/handler.go +++ b/internal/signaling/handler.go @@ -66,6 +66,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 { @@ -104,6 +119,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) diff --git a/internal/signaling/types.go b/internal/signaling/types.go index 243cb40..6a29690 100644 --- a/internal/signaling/types.go +++ b/internal/signaling/types.go @@ -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"` diff --git a/lib/signaling.ts b/lib/signaling.ts index 76ae4a4..b8042de 100644 --- a/lib/signaling.ts +++ b/lib/signaling.ts @@ -209,6 +209,8 @@ export default class Signaling extends EventEmitter { case 'credentials': this.emit('credentials', packet) break + case 'ping': + break } } catch (e) { const error = new SignalingError('unknown-error', e as string) diff --git a/lib/types.ts b/lib/types.ts index b9f8c84..d2084bd 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -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