Skip to content

Commit

Permalink
feat: ✨ add StartForever func to client
Browse files Browse the repository at this point in the history
Begin client and launch a goroutine with a loop to continuously restart the tunnel if it closes.
  • Loading branch information
onionj committed Feb 23, 2024
1 parent e03c0b8 commit 484f2cb
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
40 changes: 40 additions & 0 deletions muxr/client.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package muxr

import (
"fmt"
"log"
"net/http"
"sync"
"time"

"github.com/gorilla/websocket"
)
Expand Down Expand Up @@ -78,6 +80,39 @@ func (c *Client) Start() error {
return nil
}

// Begin client and launch a goroutine with a loop to continuously restart the tunnel if it closes.
func (c *Client) StartForever() (closer func(), err error) {
exitChan := make(chan struct{}, 1)
err = c.Start()
if err != nil {
return nil, err
}

go func() {
for {
select {
case <-exitChan:
fmt.Println("muxr StartForEver: closed")
return
default:
time.Sleep(time.Second / 50)
if c.isClosed {
fmt.Println("muxr StartForEver: restarting")
err = c.Start()
if err != nil {
fmt.Println("muxr StartForEver error:", err)
}
}
}
}
}()

return func() {
exitChan <- struct{}{}
c.Stop()
}, nil
}

func (c *Client) Stop() {
c.Lock()
defer c.Unlock()
Expand All @@ -101,6 +136,11 @@ func (c *Client) getStreamId() uint32 {
func (c *Client) Dial() (*Stream, error) {
streamId := c.getStreamId()

loopCounter := 0
for ; c.isClosed && loopCounter < 10; loopCounter++ {
time.Sleep(time.Second / 10)
}

if c.isClosed {
return nil, ErrTunnelClosed
}
Expand Down
2 changes: 1 addition & 1 deletion muxr/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package muxr
import "errors"

const (
VERSION string = "v0.3.1"
VERSION string = "v0.4.0"
NUM_BYTES_HEADER = 7
TYPE_INITIAL uint8 = 1 // 0000 0001
TYPE_DATA uint8 = 2 // 0000 0010
Expand Down
1 change: 0 additions & 1 deletion muxr/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ type Stream struct {

var ErrStreamClosed = errors.New("stream closed")

// expirationTime: If the stream remains inactive for a certain period, it will be automatically terminated or destroyed.
func newStream(
id uint32,
connAdaptor *ConnAdaptor,
Expand Down

0 comments on commit 484f2cb

Please sign in to comment.