Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b71e8121e2 | |||
| 9c6db30550 | |||
| bc2017e67d | |||
| cd4a239f14 | |||
| 0d0de32d21 | |||
| 88ae539f54 | |||
| 78a5b21531 | |||
| e011931436 | |||
| 70d9a37a4e | |||
| 2ab2e07b9b | |||
| 9a9c65c24c | |||
| 8a11ce0103 | |||
| cf63683c9c | |||
| 92bd56aac0 | |||
| b4e7238b0b | |||
| b092e36987 | |||
| 4f956b8fe9 | |||
| 967b8a98b3 | |||
| d09d389011 | |||
| c550701dfa | |||
| 2225391fc3 | |||
| 9f8ee49b5c | |||
| 735f55858e | |||
| 5e5df9090f | |||
| 1537e58444 |
4
go.mod
4
go.mod
@@ -4,4 +4,6 @@ go 1.24.5
|
|||||||
|
|
||||||
require github.com/gorilla/websocket v1.5.3
|
require github.com/gorilla/websocket v1.5.3
|
||||||
|
|
||||||
require git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 // indirect
|
require git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0
|
||||||
|
|
||||||
|
require git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48 // indirect
|
||||||
|
|||||||
2
go.sum
2
go.sum
@@ -1,4 +1,6 @@
|
|||||||
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 h1:KnNc40SrYsg0cksIIcQy/ca6bunkGADQOs1u7O/E+iY=
|
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0 h1:KnNc40SrYsg0cksIIcQy/ca6bunkGADQOs1u7O/E+iY=
|
||||||
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0/go.mod h1:9DvvHc2UZhBwEs63NgO4IhiuHnBNtTuBkTJgiMnnCss=
|
git.neurocipta.com/rogerferdinan/custom-rwmutex v1.0.0/go.mod h1:9DvvHc2UZhBwEs63NgO4IhiuHnBNtTuBkTJgiMnnCss=
|
||||||
|
git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48 h1:4wXSbEuwFd2gycaaGP35bjUkKEEO6WcVfJ6cetEyT5s=
|
||||||
|
git.neurocipta.com/rogerferdinan/safe-map v0.0.0-20251011004629-ab0b119a7c48/go.mod h1:QtIxG0BYCCq8a5qyklpSHA8qWUvKr+mfl42qF9QxTc0=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package internal
|
package internal
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"log"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -24,9 +23,9 @@ type Client struct {
|
|||||||
func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
|
func NewClient(conn *websocket.Conn, subscribedPath string) *Client {
|
||||||
return &Client{
|
return &Client{
|
||||||
Conn: conn,
|
Conn: conn,
|
||||||
Send: make(chan []byte, 64),
|
Send: make(chan []byte, 2),
|
||||||
SubscribedPath: subscribedPath,
|
SubscribedPath: subscribedPath,
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}, 1),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,10 +38,10 @@ type Hub struct {
|
|||||||
|
|
||||||
func NewHub() *Hub {
|
func NewHub() *Hub {
|
||||||
return &Hub{
|
return &Hub{
|
||||||
Broadcast: make(chan []byte),
|
Broadcast: make(chan []byte, 1),
|
||||||
Register: make(chan *Client),
|
Register: make(chan *Client, 1),
|
||||||
Unregister: make(chan *Client),
|
Unregister: make(chan *Client, 1),
|
||||||
Clients: make(map[*Client]bool),
|
Clients: make(map[*Client]bool, 0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,14 +117,14 @@ func ReadPump(c *Client, h *Hub) {
|
|||||||
for {
|
for {
|
||||||
messageType, message, err := c.Conn.ReadMessage()
|
messageType, message, err := c.Conn.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
||||||
log.Printf("WebSocket error: %v", err)
|
log.Printf("WebSocket error: %v", err)
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
if messageType == websocket.TextMessage {
|
if messageType == websocket.TextMessage {
|
||||||
fmt.Printf("Received: %s\n", message)
|
log.Printf("Received: %s\n", message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,62 +6,31 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
|
custom_rwmutex "git.neurocipta.com/rogerferdinan/custom-rwmutex"
|
||||||
|
safemap "git.neurocipta.com/rogerferdinan/safe-map"
|
||||||
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
"git.neurocipta.com/rogerferdinan/safe-web-socket/internal"
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
pingPeriod = 10 * time.Second
|
pingPeriod = 10 * time.Second
|
||||||
|
readDeadline = 30 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
type SafeMap[K comparable, V any] struct {
|
type MessageType uint
|
||||||
m sync.Map
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSafeMap[K comparable, V any]() *SafeMap[K, V] {
|
const (
|
||||||
return &SafeMap[K, V]{
|
MessageTypeText MessageType = websocket.TextMessage
|
||||||
m: sync.Map{},
|
MessageTypePing MessageType = websocket.PingMessage
|
||||||
}
|
MessageTypePong MessageType = websocket.PongMessage
|
||||||
}
|
MessageTypeClose MessageType = websocket.CloseMessage
|
||||||
|
)
|
||||||
|
|
||||||
func (sm *SafeMap[K, V]) Store(key K, value V) {
|
type Message struct {
|
||||||
sm.m.Store(key, value)
|
MessageType MessageType
|
||||||
}
|
Data []byte
|
||||||
|
|
||||||
func (sm *SafeMap[K, V]) Load(key K) (value V, ok bool) {
|
|
||||||
val, loaded := sm.m.Load(key)
|
|
||||||
if !loaded {
|
|
||||||
return *new(V), false
|
|
||||||
}
|
|
||||||
return val.(V), true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sm *SafeMap[K, V]) Delete(key K) {
|
|
||||||
sm.m.Delete(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sm *SafeMap[K, V]) Range(f func(K, V) bool) {
|
|
||||||
sm.m.Range(func(key, value any) bool {
|
|
||||||
k, ok1 := key.(K)
|
|
||||||
v, ok2 := value.(V)
|
|
||||||
if !ok1 || !ok2 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return f(k, v)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sm *SafeMap[K, V]) Len() int {
|
|
||||||
count := 0
|
|
||||||
sm.Range(func(_ K, _ V) bool {
|
|
||||||
count++
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
return count
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type SafeWebsocketClientBuilder struct {
|
type SafeWebsocketClientBuilder struct {
|
||||||
@@ -69,6 +38,7 @@ type SafeWebsocketClientBuilder struct {
|
|||||||
basePort *uint16 `nil_checker:"required"`
|
basePort *uint16 `nil_checker:"required"`
|
||||||
path *string
|
path *string
|
||||||
rawQuery *string
|
rawQuery *string
|
||||||
|
isDrop *bool
|
||||||
useTLS *bool
|
useTLS *bool
|
||||||
channelSize *int64
|
channelSize *int64
|
||||||
}
|
}
|
||||||
@@ -102,6 +72,11 @@ func (b *SafeWebsocketClientBuilder) RawQuery(rawQuery string) *SafeWebsocketCli
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *SafeWebsocketClientBuilder) IsDrop(isDrop bool) *SafeWebsocketClientBuilder {
|
||||||
|
b.isDrop = &isDrop
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder {
|
func (b *SafeWebsocketClientBuilder) ChannelSize(channelSize int64) *SafeWebsocketClientBuilder {
|
||||||
b.channelSize = &channelSize
|
b.channelSize = &channelSize
|
||||||
return b
|
return b
|
||||||
@@ -112,9 +87,15 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var useTLS bool
|
// var useTLS bool
|
||||||
if b.useTLS != nil {
|
if b.useTLS == nil {
|
||||||
useTLS = *b.useTLS
|
useTLS := true
|
||||||
|
b.useTLS = &useTLS
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.isDrop == nil {
|
||||||
|
isDrop := true
|
||||||
|
b.isDrop = &isDrop
|
||||||
}
|
}
|
||||||
|
|
||||||
if b.channelSize == nil {
|
if b.channelSize == nil {
|
||||||
@@ -125,7 +106,8 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|||||||
wsClient := SafeWebsocketClient{
|
wsClient := SafeWebsocketClient{
|
||||||
baseHost: *b.baseHost,
|
baseHost: *b.baseHost,
|
||||||
basePort: *b.basePort,
|
basePort: *b.basePort,
|
||||||
useTLS: useTLS,
|
useTLS: *b.useTLS,
|
||||||
|
isDrop: *b.isDrop,
|
||||||
path: b.path,
|
path: b.path,
|
||||||
rawQuery: b.rawQuery,
|
rawQuery: b.rawQuery,
|
||||||
dataChannel: make(chan []byte, *b.channelSize),
|
dataChannel: make(chan []byte, *b.channelSize),
|
||||||
@@ -133,7 +115,8 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
reconnectCh: make(chan struct{}, 1),
|
reconnectCh: make(chan struct{}, 1),
|
||||||
isConnected: false,
|
isConnected: false,
|
||||||
doneMap: NewSafeMap[string, chan struct{}](),
|
doneMap: safemap.NewSafeMap[string, chan struct{}](),
|
||||||
|
writeChan: make(chan Message, 1),
|
||||||
}
|
}
|
||||||
|
|
||||||
go wsClient.reconnectHandler()
|
go wsClient.reconnectHandler()
|
||||||
@@ -146,20 +129,26 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SafeWebsocketClient struct {
|
type SafeWebsocketClient struct {
|
||||||
baseHost string
|
baseHost string
|
||||||
basePort uint16
|
basePort uint16
|
||||||
useTLS bool
|
isDrop bool
|
||||||
path *string
|
useTLS bool
|
||||||
rawQuery *string
|
path *string
|
||||||
dataChannel chan []byte
|
rawQuery *string
|
||||||
mu *custom_rwmutex.CustomRwMutex
|
|
||||||
conn *websocket.Conn
|
mu *custom_rwmutex.CustomRwMutex
|
||||||
cancelFuncs []context.CancelFunc
|
conn *websocket.Conn
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
|
cancelFuncs []context.CancelFunc
|
||||||
|
dataChannel chan []byte
|
||||||
|
|
||||||
reconnectCh chan struct{}
|
reconnectCh chan struct{}
|
||||||
reconnectChans []chan struct{}
|
reconnectChans []chan struct{}
|
||||||
isConnected bool
|
isConnected bool
|
||||||
doneMap *SafeMap[string, chan struct{}]
|
doneMap *safemap.SafeMap[string, chan struct{}]
|
||||||
|
|
||||||
|
writeChan chan Message
|
||||||
|
pongChan chan error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) connect() error {
|
func (wsClient *SafeWebsocketClient) connect() error {
|
||||||
@@ -187,41 +176,161 @@ func (wsClient *SafeWebsocketClient) connect() error {
|
|||||||
return fmt.Errorf("failed to connect to %s: %w", wsClient.baseHost, err)
|
return fmt.Errorf("failed to connect to %s: %w", wsClient.baseHost, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
conn.SetPingHandler(func(pingData string) error {
|
pingCtx, pingCancel := context.WithCancel(context.Background())
|
||||||
if err := conn.WriteMessage(websocket.PongMessage, []byte(pingData)); err != nil {
|
|
||||||
if err == websocket.ErrCloseSent {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
wsClient.mu.WriteHandler(func() error {
|
wsClient.mu.WriteHandler(func() error {
|
||||||
if wsClient.conn != nil {
|
|
||||||
wsClient.conn.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
wsClient.conn = conn
|
|
||||||
|
|
||||||
wsClient.isConnected = true
|
|
||||||
|
|
||||||
pingCtx, pingCancel := context.WithCancel(context.Background())
|
|
||||||
go wsClient.startPingTicker(pingCtx)
|
|
||||||
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, pingCancel)
|
||||||
|
|
||||||
receiverCtx, receiverCancel := context.WithCancel(context.Background())
|
|
||||||
go wsClient.startReceiveHandler(receiverCtx)
|
|
||||||
wsClient.cancelFuncs = append(wsClient.cancelFuncs, receiverCancel)
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
go wsClient.startPingTicker(pingCtx)
|
||||||
|
|
||||||
|
if wsClient.conn != nil {
|
||||||
|
wsClient.conn.Close()
|
||||||
|
}
|
||||||
|
wsClient.conn = conn
|
||||||
|
wsClient.isConnected = true
|
||||||
|
|
||||||
|
go wsClient.writePump()
|
||||||
|
go wsClient.readPump()
|
||||||
|
|
||||||
|
conn.SetPingHandler(func(pingData string) error {
|
||||||
|
wsClient.writeChan <- Message{
|
||||||
|
MessageType: MessageTypePong,
|
||||||
|
Data: []byte(pingData),
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-wsClient.pongChan:
|
||||||
|
return err
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) writePump() {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
var c *websocket.Conn
|
||||||
|
wsClient.mu.ReadHandler(func() error {
|
||||||
|
c = wsClient.conn
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("Writer canceled by context")
|
||||||
|
return
|
||||||
|
case data := <-wsClient.writeChan:
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.WriteMessage(int(data.MessageType), data.Data); err != nil {
|
||||||
|
log.Printf("error on write message: %v\n", err)
|
||||||
|
if data.MessageType == MessageTypePong {
|
||||||
|
wsClient.pongChan <- err
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (wsClient *SafeWebsocketClient) readPump() {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
wsClient.mu.WriteHandler(func() error {
|
||||||
|
wsClient.cancelFuncs = append(wsClient.cancelFuncs, cancel)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
var c *websocket.Conn
|
||||||
|
wsClient.mu.ReadHandler(func() error {
|
||||||
|
c = wsClient.conn
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if wsClient.isDrop {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("Reader canceled by context")
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
||||||
|
log.Printf("error on read deadline: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
messageType, data, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error on read message: %v\n", err)
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if messageType != websocket.TextMessage {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case wsClient.dataChannel <- data:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
log.Println("Data channel full, dropping message")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("Reader canceled by context")
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
if c == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.SetReadDeadline(time.Now().Add(readDeadline)); err != nil {
|
||||||
|
log.Printf("error on read deadline: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
messageType, data, err := c.ReadMessage()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error on read message: %v\n", err)
|
||||||
|
wsClient.triggerReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if messageType != websocket.TextMessage {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case wsClient.dataChannel <- data:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
||||||
ticker := time.NewTicker(pingPeriod)
|
ticker := time.NewTicker(pingPeriod)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
@@ -229,53 +338,12 @@ func (wsClient *SafeWebsocketClient) startPingTicker(ctx context.Context) {
|
|||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
log.Println("ping ticker stopped")
|
log.Println("ping ticker canceled by context")
|
||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
wsClient.mu.WriteHandler(func() error {
|
wsClient.writeChan <- Message{
|
||||||
if wsClient.conn == nil {
|
MessageType: websocket.PingMessage,
|
||||||
return fmt.Errorf("connection closed")
|
Data: []byte{},
|
||||||
}
|
|
||||||
if err := wsClient.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
|
||||||
log.Printf("Ping failed: %v. Will attempt reconnect.", err)
|
|
||||||
wsClient.triggerReconnect()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) startReceiveHandler(ctx context.Context) {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
log.Println("receive handler stopped")
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
if err := wsClient.mu.ReadHandler(func() error {
|
|
||||||
conn := wsClient.conn
|
|
||||||
|
|
||||||
if conn == nil {
|
|
||||||
wsClient.triggerReconnect()
|
|
||||||
return fmt.Errorf("connection closed")
|
|
||||||
}
|
|
||||||
_, message, err := conn.ReadMessage()
|
|
||||||
if err != nil {
|
|
||||||
wsClient.triggerReconnect()
|
|
||||||
return fmt.Errorf("failed to read message: %v", err)
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case wsClient.dataChannel <- message:
|
|
||||||
case <-ctx.Done():
|
|
||||||
log.Println("Reconnect handler stopped")
|
|
||||||
return nil
|
|
||||||
default:
|
|
||||||
log.Println("Data channel full, dropping message")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}); err != nil {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -295,13 +363,18 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|||||||
select {
|
select {
|
||||||
case <-wsClient.reconnectCh:
|
case <-wsClient.reconnectCh:
|
||||||
log.Println("Reconnect triggered")
|
log.Println("Reconnect triggered")
|
||||||
if wsClient.cancelFuncs != nil {
|
|
||||||
for _, cancel := range wsClient.cancelFuncs {
|
wsClient.mu.ReadHandler(func() error {
|
||||||
cancel()
|
if wsClient.cancelFuncs != nil {
|
||||||
|
for _, cancel := range wsClient.cancelFuncs {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
wsClient.isConnected = false
|
wsClient.isConnected = false
|
||||||
time.Sleep(100 * time.Millisecond)
|
// time.Sleep(100 * time.Millisecond)
|
||||||
|
|
||||||
isInnerLoop := true
|
isInnerLoop := true
|
||||||
for isInnerLoop {
|
for isInnerLoop {
|
||||||
@@ -320,6 +393,8 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|||||||
isInnerLoop = false
|
isInnerLoop = false
|
||||||
continue
|
continue
|
||||||
case <-wsClient.ctx.Done():
|
case <-wsClient.ctx.Done():
|
||||||
|
log.Println("reconnect handler stopped due to client shutdown")
|
||||||
|
wsClient.Close()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -337,7 +412,7 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) ReconnectChannel() <-chan struct{} {
|
func (wsClient *SafeWebsocketClient) ReconnectChannel() <-chan struct{} {
|
||||||
reconnectCh := make(chan struct{})
|
reconnectCh := make(chan struct{}, 1)
|
||||||
wsClient.mu.WriteHandler(func() error {
|
wsClient.mu.WriteHandler(func() error {
|
||||||
wsClient.reconnectChans = append(wsClient.reconnectChans, reconnectCh)
|
wsClient.reconnectChans = append(wsClient.reconnectChans, reconnectCh)
|
||||||
return nil
|
return nil
|
||||||
@@ -350,31 +425,37 @@ func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte {
|
|||||||
return wsClient.dataChannel
|
return wsClient.dataChannel
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) WriteJSON(message any) error {
|
func (wsClient *SafeWebsocketClient) CloseDataChannel() {
|
||||||
return wsClient.mu.WriteHandler(func() error {
|
close(wsClient.dataChannel)
|
||||||
return wsClient.conn.WriteJSON(message)
|
}
|
||||||
})
|
|
||||||
|
func (wsClient *SafeWebsocketClient) Write(data []byte) error {
|
||||||
|
wsClient.writeChan <- Message{
|
||||||
|
MessageType: MessageTypeText,
|
||||||
|
Data: data,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wsClient *SafeWebsocketClient) Close() error {
|
func (wsClient *SafeWebsocketClient) Close() error {
|
||||||
wsClient.mu.WriteHandler(func() error {
|
wsClient.mu.ReadHandler(func() error {
|
||||||
if wsClient.cancelFuncs != nil {
|
if wsClient.cancelFuncs != nil {
|
||||||
for _, cancel := range wsClient.cancelFuncs {
|
for _, cancel := range wsClient.cancelFuncs {
|
||||||
cancel()
|
cancel()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if wsClient.reconnectChans != nil {
|
|
||||||
for _, reconnectChan := range wsClient.reconnectChans {
|
|
||||||
close(reconnectChan)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if wsClient.conn != nil {
|
|
||||||
wsClient.conn.Close()
|
|
||||||
}
|
|
||||||
wsClient.isConnected = false
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if wsClient.reconnectChans != nil {
|
||||||
|
for _, reconnectChan := range wsClient.reconnectChans {
|
||||||
|
close(reconnectChan)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if wsClient.conn != nil {
|
||||||
|
wsClient.conn.Close()
|
||||||
|
}
|
||||||
|
wsClient.isConnected = false
|
||||||
close(wsClient.dataChannel)
|
close(wsClient.dataChannel)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ func main() {
|
|||||||
BasePort(8080).
|
BasePort(8080).
|
||||||
Path("/ws/test/data_1").
|
Path("/ws/test/data_1").
|
||||||
UseTLS(false).
|
UseTLS(false).
|
||||||
|
ChannelSize(30).
|
||||||
Build(ctx)
|
Build(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
@@ -43,6 +44,7 @@ func main() {
|
|||||||
dataChannel := wsClient.DataChannel()
|
dataChannel := wsClient.DataChannel()
|
||||||
|
|
||||||
for data := range dataChannel {
|
for data := range dataChannel {
|
||||||
|
// _ = data
|
||||||
fmt.Println(string(data))
|
fmt.Println(string(data))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user