2022-09-14 19:09:39 +08:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
ID string
|
|
|
|
Socket *websocket.Conn
|
|
|
|
Msg chan []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWsClient(ID string, socket *websocket.Conn) *Client {
|
|
|
|
return &Client{
|
|
|
|
ID: ID,
|
|
|
|
Socket: socket,
|
|
|
|
Msg: make(chan []byte, 100),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Read() {
|
|
|
|
defer func() {
|
|
|
|
close(c.Msg)
|
|
|
|
}()
|
|
|
|
for {
|
|
|
|
_, message, err := c.Socket.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2023-06-28 14:50:10 +08:00
|
|
|
ProcessData(c, message)
|
2022-09-14 19:09:39 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Write() {
|
|
|
|
defer func() {
|
|
|
|
c.Socket.Close()
|
|
|
|
}()
|
|
|
|
for {
|
2023-02-01 15:50:39 +08:00
|
|
|
message, ok := <-c.Msg
|
|
|
|
if !ok {
|
|
|
|
return
|
2022-09-14 19:09:39 +08:00
|
|
|
}
|
2023-02-01 15:50:39 +08:00
|
|
|
_ = c.Socket.WriteMessage(websocket.TextMessage, message)
|
2022-09-14 19:09:39 +08:00
|
|
|
}
|
|
|
|
}
|