Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

fix: Add context to negotiate RTC func #394

Merged
merged 6 commits into from
Jul 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions wsnet/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ func DialWebsocket(ctx context.Context, broker string, netOpts *DialOptions, wsO
// We should close the socket intentionally.
_ = conn.Close(websocket.StatusInternalError, "an error occurred")
}()
return Dial(nconn, netOpts)
return Dial(ctx, nconn, netOpts)
}

// Dial negotiates a connection to a listener.
func Dial(conn net.Conn, options *DialOptions) (*Dialer, error) {
func Dial(ctx context.Context, conn net.Conn, options *DialOptions) (*Dialer, error) {
if options == nil {
options = &DialOptions{}
}
Expand Down Expand Up @@ -121,7 +121,7 @@ func Dial(conn net.Conn, options *DialOptions) (*Dialer, error) {
connClosers: []io.Closer{ctrl},
}

return dialer, dialer.negotiate()
return dialer, dialer.negotiate(ctx)
}

// Dialer enables arbitrary dialing to any network and address
Expand All @@ -138,7 +138,7 @@ type Dialer struct {
pingMut sync.Mutex
}

func (d *Dialer) negotiate() (err error) {
func (d *Dialer) negotiate(ctx context.Context) (err error) {
var (
decoder = json.NewDecoder(d.conn)
errCh = make(chan error)
Expand All @@ -153,7 +153,7 @@ func (d *Dialer) negotiate() (err error) {
defer func() {
_ = d.conn.Close()
}()
err := waitForConnectionOpen(context.Background(), d.rtc)
err := waitForConnectionOpen(ctx, d.rtc)
if err != nil {
errCh <- err
return
Expand Down
11 changes: 8 additions & 3 deletions wsnet/rtc.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,11 +242,16 @@ func waitForConnectionOpen(ctx context.Context, conn *webrtc.PeerConnection) err
if conn.ConnectionState() == webrtc.PeerConnectionStateConnected {
return nil
}
ctx, cancelFunc := context.WithTimeout(ctx, time.Second*15)
defer cancelFunc()
var cancel context.CancelFunc
if _, deadlineSet := ctx.Deadline(); deadlineSet {
ctx, cancel = context.WithCancel(ctx)
} else {
ctx, cancel = context.WithTimeout(ctx, time.Second*15)
}
defer cancel()
conn.OnConnectionStateChange(func(pcs webrtc.PeerConnectionState) {
if pcs == webrtc.PeerConnectionStateConnected {
cancelFunc()
cancel()
}
})
<-ctx.Done()
Expand Down