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