feat: ctx + ping
This commit is contained in:
parent
60635005e7
commit
54565f6af8
|
|
@ -1,6 +1,7 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
|
@ -15,6 +16,9 @@ const (
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ws := websocket.NewWebSocketClient(
|
ws := websocket.NewWebSocketClient(
|
||||||
|
// ctx
|
||||||
|
context.Background(),
|
||||||
|
|
||||||
// onOpen
|
// onOpen
|
||||||
func(ws *websocket.WebSocketClient) {
|
func(ws *websocket.WebSocketClient) {
|
||||||
log.Println("Connected")
|
log.Println("Connected")
|
||||||
|
|
|
||||||
|
|
@ -25,11 +25,12 @@ type WebSocketClient struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWebSocketClient(
|
func NewWebSocketClient(
|
||||||
|
ctx context.Context,
|
||||||
onOpen func(ws *WebSocketClient),
|
onOpen func(ws *WebSocketClient),
|
||||||
onClose func(ws *WebSocketClient),
|
onClose func(ws *WebSocketClient),
|
||||||
onMessage func(ws *WebSocketClient, payload []byte),
|
onMessage func(ws *WebSocketClient, payload []byte),
|
||||||
) *WebSocketClient {
|
) *WebSocketClient {
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
return &WebSocketClient{
|
return &WebSocketClient{
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
cancel: cancel,
|
cancel: cancel,
|
||||||
|
|
@ -84,6 +85,7 @@ func (ws *WebSocketClient) Connect(
|
||||||
var payload []byte
|
var payload []byte
|
||||||
_, payload, err := ws.conn.Read(ws.ctx)
|
_, payload, err := ws.conn.Read(ws.ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
ws.cancel()
|
||||||
if ws.onClose != nil {
|
if ws.onClose != nil {
|
||||||
ws.onClose(ws)
|
ws.onClose(ws)
|
||||||
}
|
}
|
||||||
|
|
@ -94,6 +96,21 @@ func (ws *WebSocketClient) Connect(
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
// Ping Sender
|
||||||
|
ws.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer ws.wg.Done()
|
||||||
|
pingTicker := time.NewTicker(time.Second * 10)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ws.ctx.Done():
|
||||||
|
return
|
||||||
|
case <-pingTicker.C:
|
||||||
|
ws.conn.Ping(ws.ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -113,3 +130,7 @@ func (ws *WebSocketClient) Disconnect() {
|
||||||
func (ws *WebSocketClient) SendJSON(v any) error {
|
func (ws *WebSocketClient) SendJSON(v any) error {
|
||||||
return wsjson.Write(ws.ctx, ws.conn, v)
|
return wsjson.Write(ws.ctx, ws.conn, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ws *WebSocketClient) SendPing() error {
|
||||||
|
return ws.conn.Ping(ws.ctx)
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue