[add] onOpenにisReconnecting引数を追加

This commit is contained in:
shinosaki 2025-03-01 10:16:05 +00:00
parent 484c2bf522
commit fa11551e26
2 changed files with 12 additions and 7 deletions

View File

@ -16,8 +16,12 @@ const (
func main() {
ws := websocket.NewWebSocketClient(
// onOpen
func(ws *websocket.WebSocketClient) {
func(ws *websocket.WebSocketClient, isReconnecting bool) {
if isReconnecting {
log.Println("Reconnected")
} else {
log.Println("Connected")
}
},
// onClose
@ -36,7 +40,7 @@ func main() {
)
// Connect to server
if err := ws.Connect(WEBSOCKET_URL, ATTEMPTS, INTERVAL); err != nil {
if err := ws.Connect(WEBSOCKET_URL, ATTEMPTS, INTERVAL, false); err != nil {
log.Println("Failed to connect:", err)
}

View File

@ -17,13 +17,13 @@ type WebSocketClient struct {
wg sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
onOpen func(ws *WebSocketClient)
onOpen func(ws *WebSocketClient, isReconnecting bool)
onClose func(ws *WebSocketClient, isReconnecting bool)
onMessage func(ws *WebSocketClient, payload []byte)
}
func NewWebSocketClient(
onOpen func(ws *WebSocketClient),
onOpen func(ws *WebSocketClient, isReconnecting bool),
onClose func(ws *WebSocketClient, isReconnecting bool),
onMessage func(ws *WebSocketClient, payload []byte),
) *WebSocketClient {
@ -41,6 +41,7 @@ func (ws *WebSocketClient) Connect(
webSocketUrl string,
attempts int,
interval time.Duration,
isReconnecting bool,
) (err error) {
ws.URL, err = url.Parse(webSocketUrl)
if err != nil {
@ -61,7 +62,7 @@ func (ws *WebSocketClient) Connect(
}
if ws.onOpen != nil {
ws.onOpen(ws)
ws.onOpen(ws, isReconnecting)
}
// Message Handler
@ -103,7 +104,7 @@ func (ws *WebSocketClient) Disconnect(isReconnecting bool) {
func (ws *WebSocketClient) Reconnect(url string, attempts int, interval time.Duration) error {
ws.Disconnect(true)
ws.ctx, ws.cancel = context.WithCancel(context.Background())
return ws.Connect(url, attempts, interval)
return ws.Connect(url, attempts, interval, true)
}
func (ws *WebSocketClient) SendJSON(v any) error {