2022-06-12 22:39:48 +02:00
|
|
|
package wsshell
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2022-07-13 23:16:08 +02:00
|
|
|
"fmt"
|
2022-06-12 22:39:48 +02:00
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
2022-06-16 03:13:16 +02:00
|
|
|
const readWaitTimeout = 15 * time.Second
|
|
|
|
const writeWaitTimeout = 10 * time.Second
|
|
|
|
const pingPeriodTickTime = 10 * time.Second
|
2022-06-17 07:22:47 +02:00
|
|
|
const initialPingTime = 1 * time.Second
|
2022-06-16 03:13:16 +02:00
|
|
|
|
2022-06-12 22:39:48 +02:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
ReadBufferSize: 4 * 1024,
|
2022-09-05 21:42:09 +02:00
|
|
|
WriteBufferSize: 32 * 1024,
|
2022-06-12 22:39:48 +02:00
|
|
|
HandshakeTimeout: 1 * time.Second,
|
|
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
|
|
}
|
|
|
|
|
|
|
|
type WSShell struct {
|
|
|
|
Conn *websocket.Conn
|
|
|
|
RemoteAddr string
|
|
|
|
ConnId string
|
|
|
|
Query url.Values
|
|
|
|
OpenTime time.Time
|
|
|
|
NumPings int
|
|
|
|
LastPing time.Time
|
|
|
|
LastRecv time.Time
|
|
|
|
Header http.Header
|
|
|
|
|
|
|
|
CloseChan chan bool
|
|
|
|
WriteChan chan []byte
|
|
|
|
ReadChan chan []byte
|
|
|
|
}
|
|
|
|
|
2022-06-15 07:39:09 +02:00
|
|
|
func (ws *WSShell) NonBlockingWrite(data []byte) bool {
|
|
|
|
select {
|
|
|
|
case ws.WriteChan <- data:
|
|
|
|
return true
|
|
|
|
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-16 03:13:16 +02:00
|
|
|
func (ws *WSShell) WritePing() error {
|
|
|
|
now := time.Now()
|
|
|
|
pingMessage := map[string]interface{}{"type": "ping", "stime": now.Unix()}
|
|
|
|
jsonVal, _ := json.Marshal(pingMessage)
|
|
|
|
_ = ws.Conn.SetWriteDeadline(time.Now().Add(writeWaitTimeout)) // no error
|
|
|
|
err := ws.Conn.WriteMessage(websocket.TextMessage, jsonVal)
|
|
|
|
ws.NumPings++
|
|
|
|
ws.LastPing = now
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-17 07:22:47 +02:00
|
|
|
func (ws *WSShell) WriteJson(val interface{}) error {
|
2022-07-13 23:16:08 +02:00
|
|
|
if ws.IsClosed() {
|
|
|
|
return fmt.Errorf("cannot write packet, empty or closed wsshell")
|
|
|
|
}
|
2022-06-17 07:22:47 +02:00
|
|
|
barr, err := json.Marshal(val)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
ws.WriteChan <- barr
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-12 22:39:48 +02:00
|
|
|
func (ws *WSShell) WritePump() {
|
2022-11-29 21:45:19 +01:00
|
|
|
ticker := time.NewTicker(initialPingTime)
|
2022-06-12 22:39:48 +02:00
|
|
|
defer func() {
|
|
|
|
ticker.Stop()
|
|
|
|
ws.Conn.Close()
|
|
|
|
}()
|
2022-11-29 21:45:19 +01:00
|
|
|
initialPing := true
|
2022-06-12 22:39:48 +02:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
2022-06-16 03:13:16 +02:00
|
|
|
err := ws.WritePing()
|
2022-06-12 22:39:48 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("WritePump %s err: %v\n", ws.RemoteAddr, err)
|
|
|
|
return
|
|
|
|
}
|
2022-11-29 21:45:19 +01:00
|
|
|
if initialPing {
|
|
|
|
initialPing = false
|
|
|
|
ticker.Reset(pingPeriodTickTime)
|
|
|
|
}
|
2022-06-12 22:39:48 +02:00
|
|
|
|
2022-06-17 07:22:47 +02:00
|
|
|
case msgBytes, ok := <-ws.WriteChan:
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
2022-06-16 03:13:16 +02:00
|
|
|
_ = ws.Conn.SetWriteDeadline(time.Now().Add(writeWaitTimeout)) // no error
|
2022-06-12 22:39:48 +02:00
|
|
|
err := ws.Conn.WriteMessage(websocket.TextMessage, msgBytes)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("WritePump %s err: %v\n", ws.RemoteAddr, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ws *WSShell) ReadPump() {
|
2022-06-16 03:13:16 +02:00
|
|
|
readWait := readWaitTimeout
|
2022-06-12 22:39:48 +02:00
|
|
|
defer func() {
|
|
|
|
ws.Conn.Close()
|
|
|
|
}()
|
|
|
|
ws.Conn.SetReadLimit(4096)
|
|
|
|
ws.Conn.SetReadDeadline(time.Now().Add(readWait))
|
|
|
|
for {
|
|
|
|
_, message, err := ws.Conn.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("ReadPump %s Err: %v\n", ws.RemoteAddr, err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
jmsg := map[string]interface{}{}
|
|
|
|
err = json.Unmarshal(message, &jmsg)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error unmarshalling json: %v\n", err)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
ws.Conn.SetReadDeadline(time.Now().Add(readWait))
|
|
|
|
ws.LastRecv = time.Now()
|
|
|
|
if str, ok := jmsg["type"].(string); ok && str == "pong" {
|
|
|
|
// nothing
|
|
|
|
continue
|
|
|
|
}
|
2022-06-16 03:13:16 +02:00
|
|
|
if str, ok := jmsg["type"].(string); ok && str == "ping" {
|
|
|
|
now := time.Now()
|
|
|
|
pongMessage := map[string]interface{}{"type": "pong", "stime": now.Unix()}
|
|
|
|
jsonVal, _ := json.Marshal(pongMessage)
|
|
|
|
ws.WriteChan <- jsonVal
|
|
|
|
continue
|
|
|
|
}
|
2022-06-12 22:39:48 +02:00
|
|
|
ws.ReadChan <- message
|
|
|
|
}
|
2022-06-17 07:22:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ws *WSShell) IsClosed() bool {
|
|
|
|
select {
|
|
|
|
case <-ws.CloseChan:
|
|
|
|
return true
|
2022-06-12 22:39:48 +02:00
|
|
|
|
2022-06-17 07:22:47 +02:00
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
2022-06-12 22:39:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func StartWS(w http.ResponseWriter, r *http.Request) (*WSShell, error) {
|
|
|
|
conn, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
ws := WSShell{Conn: conn, ConnId: uuid.New().String(), OpenTime: time.Now()}
|
|
|
|
ws.CloseChan = make(chan bool)
|
|
|
|
ws.WriteChan = make(chan []byte, 10)
|
|
|
|
ws.ReadChan = make(chan []byte, 10)
|
|
|
|
ws.RemoteAddr = r.RemoteAddr
|
|
|
|
ws.Query = r.URL.Query()
|
|
|
|
ws.Header = r.Header
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
|
|
|
ws.WritePump()
|
|
|
|
}()
|
|
|
|
wg.Add(1)
|
|
|
|
go func() {
|
|
|
|
defer wg.Done()
|
|
|
|
ws.ReadPump()
|
|
|
|
}()
|
|
|
|
go func() {
|
|
|
|
wg.Wait()
|
|
|
|
close(ws.CloseChan)
|
|
|
|
close(ws.ReadChan)
|
|
|
|
}()
|
|
|
|
return &ws, nil
|
|
|
|
}
|