Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix concurrent writes to websocket #5

Merged
merged 1 commit into from
Aug 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions bybit_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"sync"
"time"

"github.com/google/uuid"
Expand All @@ -14,6 +15,8 @@ import (

type MessageHandler func(message string) error

var mu sync.Mutex

func (b *WebSocket) handleIncomingMessages() {
for {
_, message, err := b.conn.ReadMessage()
Expand Down Expand Up @@ -129,6 +132,8 @@ func Ping(b *WebSocket) {
for {
select {
case <-ticker.C: // Wait until the ticker sends a signal
mu.Lock()
defer mu.Unlock()
if err := b.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
fmt.Println("Failed to send ping:", err)
}
Expand All @@ -146,6 +151,8 @@ func (b *WebSocket) Disconnect() error {
}

func (b *WebSocket) Send(message string) error {
mu.Lock()
defer mu.Unlock()
return b.conn.WriteMessage(websocket.TextMessage, []byte(message))
}

Expand Down