Skip to content

Commit

Permalink
Avoid burning the CPU.
Browse files Browse the repository at this point in the history
  • Loading branch information
atik-lab committed Jan 27, 2021
1 parent 5820df5 commit 5debd22
Showing 1 changed file with 32 additions and 41 deletions.
73 changes: 32 additions & 41 deletions recws/recws.go
Expand Up @@ -54,7 +54,6 @@ type RecConn struct {
httpResp *http.Response
dialErr error
dialer *websocket.Dialer
close chan (bool)

*websocket.Conn
}
Expand Down Expand Up @@ -88,7 +87,7 @@ func (rc *RecConn) Close() {
rc.Conn.Close()
rc.mu.Unlock()
}
rc.close <- true

rc.setIsConnected(false)
}

Expand Down Expand Up @@ -291,9 +290,6 @@ func (rc *RecConn) Dial(urlStr string, reqHeader http.Header) {
log.Fatalf("Dial: %v", err)
}

// Close channel
rc.close = make(chan bool, 1)

// Config
rc.setURL(urlStr)
rc.setReqHeader(reqHeader)
Expand Down Expand Up @@ -377,8 +373,8 @@ func (rc *RecConn) keepAlive() {

for {
if !rc.IsConnected() {
rc.CloseAndReconnect()
return
time.Sleep(time.Millisecond * 100)
continue
}

if err := rc.writeControlPingMessage(); err != nil {
Expand All @@ -399,48 +395,43 @@ func (rc *RecConn) connect() {
rand.Seed(time.Now().UTC().UnixNano())

for {
select {
case <-rc.close:
return
default:
nextItvl := b.Duration()
wsConn, httpResp, err := rc.dialer.Dial(rc.url, rc.reqHeader)

rc.mu.Lock()
rc.Conn = wsConn
rc.dialErr = err
rc.isConnected = err == nil
rc.httpResp = httpResp
rc.mu.Unlock()

if err == nil {
if !rc.getNonVerbose() {
log.Printf("Dial: connection was successfully established with %s\n", rc.url)
}
nextItvl := b.Duration()
wsConn, httpResp, err := rc.dialer.Dial(rc.url, rc.reqHeader)

if rc.hasSubscribeHandler() {
if err := rc.SubscribeHandler(); err != nil {
log.Fatalf("Dial: connect handler failed with %s", err.Error())
}
if !rc.getNonVerbose() {
log.Printf("Dial: connect handler was successfully established with %s\n", rc.url)
}
}
rc.mu.Lock()
rc.Conn = wsConn
rc.dialErr = err
rc.isConnected = err == nil
rc.httpResp = httpResp
rc.mu.Unlock()

if rc.getKeepAliveTimeout() != 0 {
rc.keepAlive()
}
if err == nil {
if !rc.getNonVerbose() {
log.Printf("Dial: connection was successfully established with %s\n", rc.url)
}

return
if rc.hasSubscribeHandler() {
if err := rc.SubscribeHandler(); err != nil {
log.Fatalf("Dial: connect handler failed with %s", err.Error())
}
if !rc.getNonVerbose() {
log.Printf("Dial: connect handler was successfully established with %s\n", rc.url)
}
}

if !rc.getNonVerbose() {
log.Println(err)
log.Println("Dial: will try again in", nextItvl, "seconds.")
if rc.getKeepAliveTimeout() != 0 {
rc.keepAlive()
}

time.Sleep(nextItvl)
return
}

if !rc.getNonVerbose() {
log.Println(err)
log.Println("Dial: will try again in", nextItvl, "seconds.")
}

time.Sleep(nextItvl)
}
}

Expand Down

0 comments on commit 5debd22

Please sign in to comment.