You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nnet/client_ws.go

66 lines
1.5 KiB
Go

package nnet
import (
"crypto/tls"
"git.noahlan.cn/noahlan/nnet/config"
"git.noahlan.cn/noahlan/nnet/conn"
"git.noahlan.cn/noahlan/ntool/nlog"
"github.com/gorilla/websocket"
"github.com/jpillora/backoff"
"net/http"
"time"
)
// DialWebsocket websocket方式 连接服务器
func (ngin *Engine) DialWebsocket(url string, conf config.WSClientFullConf, evtOpts ...WsEventOption) (*conn.Connection, error) {
for _, opt := range evtOpts {
opt(conf.WSEvent)
}
ngin.ReadDeadline = conf.ReadDeadline
ngin.WriteDeadline = conf.WriteDeadline
err := ngin.setup()
if err != nil {
nlog.Errorf("%s failed to setup server, err:%v", ngin.LogPrefix(), err)
return nil, err
}
dialer := websocket.Dialer{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
HandshakeTimeout: conf.HandshakeTimeout,
ReadBufferSize: conf.ReadBufferSize,
WriteBufferSize: conf.WriteBufferSize,
EnableCompression: conf.Compression,
}
// 连接重试
b := &backoff.Backoff{
Factor: conf.RecFactor,
Jitter: true,
Min: conf.MinRecTime,
Max: conf.MaxRecTime,
}
var wsConn *websocket.Conn
for {
nextRec := b.Duration()
wsConn, _, err = dialer.Dial(url, http.Header{})
if err != nil {
ngin.evtMgr.OnConnectError(err)
time.Sleep(nextRec)
continue
}
if conf.ReadLimit != 0 {
wsConn.SetReadLimit(conf.ReadLimit)
}
break
}
nlog.Infof("%s now connect to %s...", ngin.LogPrefix(), url)
return ngin.handleWS(wsConn, conf.WSEvent), nil
}