99 lines
2.2 KiB
Go
99 lines
2.2 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
type WSConnection struct {
|
|
conn *websocket.Conn
|
|
writeLock sync.Mutex
|
|
alive bool
|
|
ReadChan chan string
|
|
WriteChan chan string
|
|
ErrorChan chan error
|
|
IdleTimeout time.Duration
|
|
PingInterval time.Duration
|
|
}
|
|
|
|
func NewConn(conn *websocket.Conn, server *WSServer) *WSConnection {
|
|
wsconn := &WSConnection{
|
|
conn: conn,
|
|
alive: true,
|
|
IdleTimeout: server.IdleTimeout,
|
|
PingInterval: server.PingInterval,
|
|
ReadChan: make(chan string, 1024),
|
|
WriteChan: make(chan string, 1024),
|
|
ErrorChan: make(chan error, 1),
|
|
}
|
|
|
|
return wsconn
|
|
}
|
|
|
|
func (ws *WSConnection) Open() {
|
|
go ws.messageReader()
|
|
go ws.messageSender()
|
|
// go ws.pinger()
|
|
}
|
|
|
|
func (ws *WSConnection) messageReader() {
|
|
log.Printf("Reading messages")
|
|
for {
|
|
_, message, err := ws.conn.ReadMessage()
|
|
if !ws.alive {
|
|
return
|
|
}
|
|
ws.conn.SetReadDeadline(time.Now().Add(ws.IdleTimeout))
|
|
if err != nil {
|
|
ws.ErrorChan <- err
|
|
return
|
|
}
|
|
log.Printf("Received: %s, %d in output channel", message, len(ws.ReadChan))
|
|
ws.ReadChan <- string(message)
|
|
}
|
|
}
|
|
|
|
func (ws *WSConnection) messageSender() {
|
|
log.Printf("Sending messages")
|
|
for {
|
|
msg := <-ws.WriteChan
|
|
if !ws.alive {
|
|
return
|
|
}
|
|
ws.writeLock.Lock()
|
|
|
|
ws.conn.SetWriteDeadline(time.Now().Add(ws.IdleTimeout))
|
|
log.Printf("Sending: %s, %d in input channel", msg, len(ws.WriteChan))
|
|
err := ws.conn.WriteMessage(websocket.TextMessage, []byte(msg))
|
|
if err != nil {
|
|
log.Printf("Error during message writing: %v", err)
|
|
ws.ErrorChan <- err
|
|
return
|
|
}
|
|
ws.writeLock.Unlock()
|
|
}
|
|
}
|
|
|
|
// func (ws *WSConnection) pinger() {
|
|
// log.Printf("Starting pinger, sleeping for %v", ws.PingInterval)
|
|
// for {
|
|
// time.Sleep(ws.PingInterval)
|
|
// if !ws.alive {
|
|
// return
|
|
// }
|
|
|
|
// log.Printf("Ping")
|
|
// ws.writeLock.Lock()
|
|
// err := ws.conn.WriteMessage(websocket.PingMessage, nil)
|
|
// if err != nil {
|
|
// log.Println("Error during ping:", err)
|
|
// ws.ErrorChan <- err
|
|
// return
|
|
// }
|
|
// ws.writeLock.Unlock()
|
|
// }
|
|
// }
|