2024-10-22 13:13:41 +02:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"time"
|
2024-10-30 09:51:59 +01:00
|
|
|
|
|
|
|
ChronoTomato "git.smsvc.net/pomodoro/ChronoTomato/pkg/models"
|
2024-10-22 13:13:41 +02:00
|
|
|
)
|
|
|
|
|
2024-10-30 09:51:59 +01:00
|
|
|
type Client ChronoTomato.GoTomatoClient // New websocket client
|
|
|
|
|
2024-10-30 11:03:18 +01:00
|
|
|
// Connects to websocket
|
2024-10-30 08:54:58 +01:00
|
|
|
func Connect(url string) Client {
|
2024-10-22 13:13:41 +02:00
|
|
|
conn, _, err := websocket.DefaultDialer.Dial(url, nil)
|
|
|
|
|
2024-11-06 09:03:25 +01:00
|
|
|
return Client{Conn: conn, Server: url, LastErr: err}
|
|
|
|
}
|
2024-10-31 07:37:50 +01:00
|
|
|
|
2024-11-06 09:03:25 +01:00
|
|
|
func (c Client) Connected() bool {
|
|
|
|
return c.Conn != nil
|
2024-10-22 13:13:41 +02:00
|
|
|
}
|
|
|
|
|
2024-10-30 11:03:18 +01:00
|
|
|
// Disconnects from websocket
|
2024-10-30 09:51:59 +01:00
|
|
|
func (c Client) Disconnect() {
|
2024-11-06 09:03:25 +01: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 09:51:59 +01:00
|
|
|
c.Conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
|
2024-10-22 13:13:41 +02:00
|
|
|
select {
|
|
|
|
case <-Done:
|
2024-10-23 19:04:52 +02:00
|
|
|
case <-time.After(time.Second):
|
2024-10-22 13:13:41 +02:00
|
|
|
}
|
|
|
|
}
|
2024-11-06 09:03:25 +01:00
|
|
|
return
|
2024-10-22 13:13:41 +02:00
|
|
|
}
|