2020-10-23 03:54:50 +13:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
2020-11-02 04:09:48 +13:00
|
|
|
"encoding/json"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
2020-10-23 03:54:50 +13:00
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
2020-11-15 04:03:12 +13:00
|
|
|
|
|
|
|
"demodesk/neko/internal/types"
|
2020-10-23 03:54:50 +13:00
|
|
|
)
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
type WebSocketCtx struct {
|
2020-11-15 04:03:12 +13:00
|
|
|
session types.Session
|
2020-11-02 04:09:48 +13:00
|
|
|
address string
|
|
|
|
ws *WebSocketManagerCtx
|
|
|
|
connection *websocket.Conn
|
|
|
|
mu sync.Mutex
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
func (socket *WebSocketCtx) Address() string {
|
|
|
|
//remote := socket.connection.RemoteAddr()
|
|
|
|
address := strings.SplitN(socket.address, ":", -1)
|
|
|
|
if len(address[0]) < 1 {
|
|
|
|
return socket.address
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
return address[0]
|
|
|
|
}
|
2020-10-23 03:54:50 +13:00
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
func (socket *WebSocketCtx) Send(v interface{}) error {
|
|
|
|
socket.mu.Lock()
|
|
|
|
defer socket.mu.Unlock()
|
2020-10-23 03:54:50 +13:00
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
if socket.connection == nil {
|
2020-10-23 03:54:50 +13:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
raw, err := json.Marshal(v)
|
2020-10-23 03:54:50 +13:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
socket.ws.logger.Debug().
|
2020-11-15 04:03:12 +13:00
|
|
|
Str("session", socket.session.ID()).
|
2020-11-02 04:09:48 +13:00
|
|
|
Str("address", socket.connection.RemoteAddr().String()).
|
|
|
|
Str("raw", string(raw)).
|
|
|
|
Msg("sending message to client")
|
2020-10-23 03:54:50 +13:00
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
return socket.connection.WriteMessage(websocket.TextMessage, raw)
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
func (socket *WebSocketCtx) Destroy() error {
|
|
|
|
if socket.connection == nil {
|
|
|
|
return nil
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|
|
|
|
|
2020-11-02 04:09:48 +13:00
|
|
|
return socket.connection.Close()
|
2020-10-23 03:54:50 +13:00
|
|
|
}
|