Skip to content

Commit

Permalink
Implement websocket keepalive
Browse files Browse the repository at this point in the history
  • Loading branch information
muzzammilshahid committed Dec 27, 2024
1 parent 3c8a518 commit 4b7ec50
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 6 deletions.
3 changes: 3 additions & 0 deletions acceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ func (w *WebSocketAcceptor) Spec(subProtocol string) (serializers.Serializer, er
}

func (w *WebSocketAcceptor) Accept(conn net.Conn, config *WebSocketServerConfig) (BaseSession, error) {
if config == nil {
config = DefaultWebSocketServerConfig()
}
config.SubProtocols = w.protocols()
peer, err := UpgradeWebSocket(conn, config)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion acceptor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestAccept(t *testing.T) {
require.NotNil(t, conn)

acceptor := xconn.WebSocketAcceptor{}
session, err := acceptor.Accept(conn, xconn.DefaultWebSocketServerConfig())
session, err := acceptor.Accept(conn, nil)
require.NoError(t, err)
require.NotNil(t, session)

Expand Down
7 changes: 3 additions & 4 deletions joiner.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,6 @@ func (w *WebSocketJoiner) Join(ctx context.Context, url, realm string, config *W
w.Authenticator = auth.NewAnonymousAuthenticator("", nil)
}

if config.DialTimeout == 0 {
config.DialTimeout = time.Second * 10
}

peer, err := DialWebSocket(ctx, parsedURL, config)
if err != nil {
return nil, err
Expand All @@ -46,6 +42,9 @@ func (w *WebSocketJoiner) Join(ctx context.Context, url, realm string, config *W
}

func DialWebSocket(ctx context.Context, url *netURL.URL, config *WSDialerConfig) (Peer, error) {
if config == nil {
config = &WSDialerConfig{SubProtocol: JsonWebsocketProtocol}
}
wsDialer := ws.Dialer{
Protocols: []string{config.SubProtocol},
}
Expand Down
7 changes: 6 additions & 1 deletion peer.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package xconn

import (
"crypto/rand"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -136,8 +137,12 @@ func (c *WebSocketPeer) startPinger(keepaliveInterval time.Duration, keepaliveTi
for {
<-ticker.C
// Send a ping
err := c.writeOpFunc(c.conn, ws.OpPing, []byte("ping"))
randomBytes := make([]byte, 4)
_, err := rand.Read(randomBytes)
if err != nil {
fmt.Println("failed to generate random bytes:", err)
}
if err := c.writeOpFunc(c.conn, ws.OpPing, randomBytes); err != nil {
log.Printf("failed to send ping: %v\n", err)
_ = c.conn.Close()
return
Expand Down

0 comments on commit 4b7ec50

Please sign in to comment.