Compare commits

...

2 Commits

2 changed files with 47 additions and 16 deletions

View File

@@ -157,8 +157,8 @@ type SafeWebsocketClient struct {
cancelFuncs []context.CancelFunc cancelFuncs []context.CancelFunc
ctx context.Context ctx context.Context
reconnectCh chan struct{} reconnectCh chan struct{}
reconnectChans []chan struct{}
isConnected bool isConnected bool
doneMap *SafeMap[string, chan struct{}] doneMap *SafeMap[string, chan struct{}]
} }
@@ -301,7 +301,6 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
} }
} }
wsClient.isConnected = false wsClient.isConnected = false
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)
isInnerLoop := true isInnerLoop := true
@@ -324,7 +323,11 @@ func (wsClient *SafeWebsocketClient) reconnectHandler() {
return return
} }
} }
if wsClient.reconnectChans != nil {
for _, reconnectCh := range wsClient.reconnectChans {
reconnectCh <- struct{}{}
}
}
case <-wsClient.ctx.Done(): case <-wsClient.ctx.Done():
log.Println("reconnect handler stopped due to client shutdown") log.Println("reconnect handler stopped due to client shutdown")
wsClient.Close() wsClient.Close()
@@ -333,10 +336,26 @@ 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 { func (wsClient *SafeWebsocketClient) DataChannel() <-chan []byte {
return wsClient.dataChannel return wsClient.dataChannel
} }
func (wsClient *SafeWebsocketClient) WriteJSON(message any) error {
return wsClient.mu.WriteHandler(func() error {
return wsClient.conn.WriteJSON(message)
})
}
func (wsClient *SafeWebsocketClient) Close() error { func (wsClient *SafeWebsocketClient) Close() error {
wsClient.mu.WriteHandler(func() error { wsClient.mu.WriteHandler(func() error {
if wsClient.cancelFuncs != nil { if wsClient.cancelFuncs != nil {
@@ -344,6 +363,12 @@ func (wsClient *SafeWebsocketClient) Close() error {
cancel() cancel()
} }
} }
if wsClient.reconnectChans != nil {
for _, reconnectChan := range wsClient.reconnectChans {
close(reconnectChan)
}
}
if wsClient.conn != nil { if wsClient.conn != nil {
wsClient.conn.Close() wsClient.conn.Close()
} }

View File

@@ -34,6 +34,12 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
go func() {
for range wsClient.ReconnectChannel() {
fmt.Println("Reconnection Success")
}
}()
dataChannel := wsClient.DataChannel() dataChannel := wsClient.DataChannel()
for data := range dataChannel { for data := range dataChannel {