2020-11-26 06:36:33 +13:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
|
|
|
|
"demodesk/neko/internal/types"
|
|
|
|
)
|
|
|
|
|
|
|
|
type WebSocketPeerCtx struct {
|
2021-02-15 05:11:21 +13:00
|
|
|
mu sync.Mutex
|
2020-11-26 06:36:33 +13:00
|
|
|
session types.Session
|
2021-02-15 05:11:21 +13:00
|
|
|
manager *WebSocketManagerCtx
|
2020-11-26 06:36:33 +13:00
|
|
|
connection *websocket.Conn
|
|
|
|
}
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
func (peer *WebSocketPeerCtx) Send(v interface{}) error {
|
|
|
|
peer.mu.Lock()
|
|
|
|
defer peer.mu.Unlock()
|
2020-11-26 06:36:33 +13:00
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
if peer.connection == nil {
|
2020-11-26 06:36:33 +13:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
raw, err := json.Marshal(v)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
peer.manager.logger.Debug().
|
|
|
|
Str("session", peer.session.ID()).
|
|
|
|
Str("address", peer.connection.RemoteAddr().String()).
|
2020-11-26 06:36:33 +13:00
|
|
|
Str("raw", string(raw)).
|
|
|
|
Msg("sending message to client")
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
return peer.connection.WriteMessage(websocket.TextMessage, raw)
|
2020-11-26 06:36:33 +13:00
|
|
|
}
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
func (peer *WebSocketPeerCtx) Destroy() error {
|
|
|
|
if peer.connection == nil {
|
2020-11-26 06:36:33 +13:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-15 05:11:21 +13:00
|
|
|
return peer.connection.Close()
|
2020-11-26 06:36:33 +13:00
|
|
|
}
|