server-go/socket/readwrite.go

101 lines
1.9 KiB
Go
Raw Normal View History

2018-04-05 15:15:29 +00:00
package socket
2018-04-04 13:28:35 +00:00
import (
"fmt"
"io"
"time"
2018-04-13 09:50:14 +00:00
logging "git.loafle.net/commons/logging-go"
2018-04-04 13:28:35 +00:00
)
2018-04-04 16:51:34 +00:00
func connReadHandler(readWriteHandler ReadWriteHandler, conn Conn, stopChan <-chan struct{}, doneChan chan<- error, readChan chan<- []byte) {
2018-04-04 13:28:35 +00:00
var (
message []byte
err error
)
defer func() {
doneChan <- err
}()
2018-04-13 09:45:24 +00:00
conn.SetReadLimit(readWriteHandler.GetMaxMessageSize())
conn.SetReadDeadline(time.Now().Add(readWriteHandler.GetReadTimeout()))
2018-04-04 13:28:35 +00:00
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(readWriteHandler.GetPongTimeout()))
return nil
})
for {
readMessageChan := make(chan struct{})
go func() {
_, message, err = conn.ReadMessage()
close(readMessageChan)
}()
select {
case <-stopChan:
<-readMessageChan
return
case <-readMessageChan:
}
if nil != err {
if IsUnexpectedCloseError(err, CloseGoingAway, CloseAbnormalClosure) {
err = fmt.Errorf("Read error %v", err)
}
return
}
readChan <- message
}
}
2018-04-04 16:51:34 +00:00
func connWriteHandler(readWriteHandler ReadWriteHandler, conn Conn, stopChan <-chan struct{}, doneChan chan<- error, writeChan <-chan []byte) {
2018-04-04 13:28:35 +00:00
var (
wc io.WriteCloser
message []byte
ok bool
err error
)
defer func() {
doneChan <- err
}()
ticker := time.NewTicker(readWriteHandler.GetPingPeriod())
defer func() {
ticker.Stop()
}()
for {
select {
case message, ok = <-writeChan:
2018-04-13 09:45:24 +00:00
conn.SetWriteDeadline(time.Now().Add(readWriteHandler.GetWriteTimeout()))
2018-04-04 13:28:35 +00:00
if !ok {
conn.WriteMessage(CloseMessage, []byte{})
return
}
wc, err = conn.NextWriter(TextMessage)
if err != nil {
2018-04-13 09:50:14 +00:00
logging.Logger().Debug(err)
2018-04-04 13:28:35 +00:00
return
}
wc.Write(message)
if err = wc.Close(); nil != err {
2018-04-13 09:50:14 +00:00
logging.Logger().Debug(err)
2018-04-04 13:28:35 +00:00
return
}
case <-ticker.C:
conn.SetWriteDeadline(time.Now().Add(readWriteHandler.GetPingTimeout()))
if err = conn.WriteMessage(PingMessage, nil); nil != err {
return
}
case <-stopChan:
return
}
}
}