100 lines
1.8 KiB
Go
100 lines
1.8 KiB
Go
package overflow_gateway_websocket
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.loafle.net/overflow/overflow_gateway_websocket/websocket"
|
|
)
|
|
|
|
type Socket interface {
|
|
ID() string
|
|
Conn() *websocket.Conn
|
|
Path() string
|
|
run()
|
|
}
|
|
|
|
type socket struct {
|
|
id string
|
|
o *SocketOptions
|
|
conn *websocket.Conn
|
|
path string
|
|
messageType int
|
|
writeMTX sync.Mutex
|
|
}
|
|
|
|
func NewSocket(id string, path string, o *SocketOptions, conn *websocket.Conn) Socket {
|
|
c := &socket{
|
|
id: id,
|
|
o: o,
|
|
conn: conn,
|
|
path: path,
|
|
messageType: websocket.TextMessage,
|
|
}
|
|
|
|
return c
|
|
}
|
|
|
|
func (soc *socket) ID() string {
|
|
return soc.id
|
|
}
|
|
|
|
func (soc *socket) Conn() *websocket.Conn {
|
|
return soc.conn
|
|
}
|
|
|
|
func (soc *socket) Path() string {
|
|
return soc.path
|
|
}
|
|
|
|
func (soc *socket) run() {
|
|
hasReadTimeout := soc.o.ReadTimeout > 0
|
|
soc.conn.SetReadLimit(soc.o.MaxMessageSize)
|
|
|
|
defer func() {
|
|
soc.o.onDisconnected(soc)
|
|
}()
|
|
|
|
for {
|
|
if hasReadTimeout {
|
|
soc.conn.SetReadDeadline(time.Now().Add(soc.o.ReadTimeout))
|
|
}
|
|
|
|
// messageType, data, err := c.conn.ReadMessage()
|
|
messageType, r, err := soc.conn.NextReader()
|
|
if err != nil {
|
|
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
|
|
//c.fireError(err)
|
|
}
|
|
break
|
|
} else {
|
|
soc.onMessage(messageType, r)
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
func (soc *socket) onMessage(messageType int, r io.Reader) {
|
|
result := soc.o.Handler.OnMessage(soc, messageType, r)
|
|
if nil == result {
|
|
return
|
|
}
|
|
|
|
soc.writeMTX.Lock()
|
|
if writeTimeout := soc.o.WriteTimeout; writeTimeout > 0 {
|
|
err := soc.conn.SetWriteDeadline(time.Now().Add(writeTimeout))
|
|
log.Println(fmt.Errorf("%v", err))
|
|
return
|
|
}
|
|
|
|
err := soc.conn.WriteMessage(soc.messageType, result)
|
|
|
|
soc.writeMTX.Unlock()
|
|
|
|
if nil != err {
|
|
}
|
|
}
|