Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ping the websocket every 30 second disconencts are noticed. #56

Merged
merged 1 commit into from
Sep 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions internal/signaling/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
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