From 66b27082b91f1054a7318fe564a907fe91a31ea4 Mon Sep 17 00:00:00 2001 From: Roger Ferdinan Date: Mon, 29 Sep 2025 15:45:02 +0700 Subject: [PATCH] feat: adding reconnect channel for authentication purposes --- v1/client/client.go | 51 ++++++++++++++++++++++++++------------ v1/examples/client/main.go | 6 +++++ 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/v1/client/client.go b/v1/client/client.go index d1f6949..9331db2 100644 --- a/v1/client/client.go +++ b/v1/client/client.go @@ -146,20 +146,20 @@ func (b *SafeWebsocketClientBuilder) Build(ctx context.Context) (*SafeWebsocketC } type SafeWebsocketClient struct { - baseHost string - basePort uint16 - useTLS bool - path *string - rawQuery *string - dataChannel chan []byte - mu *custom_rwmutex.CustomRwMutex - conn *websocket.Conn - cancelFuncs []context.CancelFunc - ctx context.Context - reconnectCh chan struct{} - isConnected bool - - doneMap *SafeMap[string, chan struct{}] + baseHost string + basePort uint16 + useTLS bool + path *string + rawQuery *string + dataChannel chan []byte + mu *custom_rwmutex.CustomRwMutex + conn *websocket.Conn + cancelFuncs []context.CancelFunc + ctx context.Context + reconnectCh chan struct{} + reconnectChans []chan struct{} + isConnected bool + doneMap *SafeMap[string, chan struct{}] } func (wsClient *SafeWebsocketClient) connect() error { @@ -301,7 +301,6 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() { } } wsClient.isConnected = false - time.Sleep(100 * time.Millisecond) isInnerLoop := true @@ -324,7 +323,11 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() { return } } - + if wsClient.reconnectChans != nil { + for _, reconnectCh := range wsClient.reconnectChans { + reconnectCh <- struct{}{} + } + } case <-wsClient.ctx.Done(): log.Println("reconnect handler stopped due to client shutdown") wsClient.Close() @@ -333,6 +336,16 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() { } } +func (wsClient *SafeWebsocketClient) ReconnectChannel() <-chan struct{} { + reconnectCh := make(chan struct{}) + wsClient.mu.WriteHandler(func() error { + wsClient.reconnectChans = append(wsClient.reconnectChans, reconnectCh) + return nil + }) + + return reconnectCh +} + func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte { return wsClient.dataChannel } @@ -350,6 +363,12 @@ func (wsClient *SafeWebsocketClient) Close() error { cancel() } } + + if wsClient.reconnectChans != nil { + for _, reconnectChan := range wsClient.reconnectChans { + close(reconnectChan) + } + } if wsClient.conn != nil { wsClient.conn.Close() } diff --git a/v1/examples/client/main.go b/v1/examples/client/main.go index deaac21..5103196 100644 --- a/v1/examples/client/main.go +++ b/v1/examples/client/main.go @@ -34,6 +34,12 @@ func main() { log.Fatal(err) } + go func() { + for range wsClient.ReconnectChannel() { + fmt.Println("Reconnection Success") + } + }() + dataChannel := wsClient.DataChannel() for data := range dataChannel {