2024-10-22 11:13:41 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
2024-10-30 08:51:59 +00:00
|
|
|
|
2024-11-20 08:32:04 +00:00
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
|
2024-10-30 08:51:59 +00:00
|
|
|
ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models"
|
2024-10-22 11:13:41 +00:00
|
|
|
)
|
|
|
|
|
2024-10-30 08:51:59 +00:00
|
|
|
type Client ChronoTomato.GoTomatoClient // New websocket client
|
|
|
|
|
2024-10-30 10:03:18 +00:00
|
|
|
// Connects to websocket
|
2024-10-30 07:54:58 +00:00
|
|
|
func Connect(url string) Client {
|
2024-10-22 11:13:41 +00:00
|
|
|
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
|
|
|
|
|
2024-11-06 08:03:25 +00:00
|
|
|
return Client{Conn: conn, Server: url, LastErr: err}
|
|
|
|
}
|
2024-10-31 06:37:50 +00:00
|
|
|
|
2024-11-06 08:03:25 +00:00
|
|
|
func (c Client) Connected() bool {
|
2024-11-20 08:32:04 +00:00
|
|
|
if c.Conn == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set a pong handler to signal when a pong is received
|
|
|
|
c.Conn.SetPongHandler(func(s string) error {
|
|
|
|
c.Conn.SetReadDeadline(time.Now().Add(10 * time.Second))
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
// Send a ping
|
|
|
|
err := c.Conn.WriteMessage(websocket.PingMessage, nil)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
2024-10-22 11:13:41 +00:00
|
|
|
}
|
|
|
|
|
2024-10-30 10:03:18 +00:00
|
|
|
// Disconnects from websocket
|
2024-10-30 08:51:59 +00:00
|
|
|
func (c Client) Disconnect() {
|
2024-11-06 08:03:25 +00:00
|
|
|
// Cleanly close the connection by sending a close message and then
|
|
|
|
// waiting (with timeout) for the server to close the connection.
|
|
|
|
if c.Connected() {
|
2024-10-30 08:51:59 +00:00
|
|
|
c.Conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
2024-10-22 11:13:41 +00:00
|
|
|
select {
|
|
|
|
case <-Done:
|
2024-10-23 17:04:52 +00:00
|
|
|
case <-time.After(time.Second):
|
2024-10-22 11:13:41 +00:00
|
|
|
}
|
|
|
|
}
|
2024-11-06 08:03:25 +00:00
|
|
|
return
|
2024-10-22 11:13:41 +00:00
|
|
|
}
|