2024-05-17 17:43:28 +02:00
|
|
|
package ws
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
2024-06-07 16:07:35 +02:00
|
|
|
"sync"
|
2024-05-17 17:43:28 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Conn struct {
|
|
|
|
*websocket.Conn
|
2024-06-07 16:07:35 +02:00
|
|
|
mu sync.Mutex
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewConn(wsConn *websocket.Conn) net.Conn {
|
|
|
|
return &Conn{
|
2024-06-07 16:07:35 +02:00
|
|
|
Conn: wsConn,
|
2024-05-17 17:43:28 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) Read(b []byte) (n int, err error) {
|
|
|
|
t, r, err := c.NextReader()
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if t != websocket.BinaryMessage {
|
|
|
|
return 0, fmt.Errorf("unexpected message type")
|
|
|
|
}
|
|
|
|
|
|
|
|
return r.Read(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) Write(b []byte) (int, error) {
|
2024-06-07 16:07:35 +02:00
|
|
|
c.mu.Lock()
|
2024-05-17 17:43:28 +02:00
|
|
|
err := c.WriteMessage(websocket.BinaryMessage, b)
|
2024-06-07 16:07:35 +02:00
|
|
|
c.mu.Unlock()
|
2024-05-17 17:43:28 +02:00
|
|
|
return len(b), err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) SetDeadline(t time.Time) error {
|
|
|
|
errR := c.SetReadDeadline(t)
|
|
|
|
errW := c.SetWriteDeadline(t)
|
|
|
|
|
|
|
|
if errR != nil {
|
|
|
|
return errR
|
|
|
|
}
|
|
|
|
|
|
|
|
if errW != nil {
|
|
|
|
return errW
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Conn) Close() error {
|
|
|
|
return c.Conn.Close()
|
|
|
|
}
|