31 lines
666 B
Go
31 lines
666 B
Go
|
package models
|
||
|
|
||
|
import (
|
||
|
"github.com/gorilla/websocket"
|
||
|
"log"
|
||
|
"sync"
|
||
|
)
|
||
|
|
||
|
// ClientCommand represents a command from the client (start/stop).
|
||
|
type ClientCommand struct {
|
||
|
Command string `json:"command"`
|
||
|
}
|
||
|
|
||
|
type Client struct {
|
||
|
Conn *websocket.Conn
|
||
|
Mutex sync.Mutex
|
||
|
}
|
||
|
|
||
|
// It automatically locks and unlocks the mutex to ensure that only one goroutine can write at a time.
|
||
|
func (c *Client) SendMessage(messageType int, data []byte) error {
|
||
|
c.Mutex.Lock()
|
||
|
defer c.Mutex.Unlock()
|
||
|
|
||
|
err := c.Conn.WriteMessage(messageType, data)
|
||
|
if err != nil {
|
||
|
log.Printf("Error writing to WebSocket: %v", err)
|
||
|
c.Conn.Close() // Close the connection on error
|
||
|
}
|
||
|
return err
|
||
|
}
|