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.

Commit 7f3cd28

Browse files
authored
feat: Add Closed func to Dialer (#381)
* feat: Add Closed func to Dialer * Fix gocyclo * Cleanup closed bool
1 parent 0d2f06b commit 7f3cd28

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

wsnet/dial.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ func Dial(conn net.Conn, iceServers []webrtc.ICEServer) (*Dialer, error) {
8585
conn: conn,
8686
ctrl: ctrl,
8787
rtc: rtc,
88+
closedChan: make(chan struct{}),
8889
connClosers: make([]io.Closer, 0),
8990
}
9091

@@ -100,6 +101,7 @@ type Dialer struct {
100101
ctrlrw datachannel.ReadWriteCloser
101102
rtc *webrtc.PeerConnection
102103

104+
closedChan chan struct{}
103105
connClosers []io.Closer
104106
connClosersMut sync.Mutex
105107
}
@@ -136,6 +138,13 @@ func (d *Dialer) negotiate() (err error) {
136138
_ = connCloser.Close()
137139
}
138140
d.connClosers = make([]io.Closer, 0)
141+
142+
select {
143+
case <-d.closedChan:
144+
return
145+
default:
146+
}
147+
close(d.closedChan)
139148
})
140149
}()
141150

@@ -184,6 +193,12 @@ func (d *Dialer) negotiate() (err error) {
184193
return <-errCh
185194
}
186195

196+
// Closed returns a channel that closes when
197+
// the connection is closed.
198+
func (d *Dialer) Closed() <-chan struct{} {
199+
return d.closedChan
200+
}
201+
187202
// Close closes the RTC connection.
188203
// All data channels dialed will be closed.
189204
func (d *Dialer) Close() error {

wsnet/dial_test.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net"
1111
"strconv"
1212
"testing"
13+
"time"
1314

1415
"github.com/pion/ice/v2"
1516
"github.com/pion/webrtc/v3"
@@ -46,7 +47,7 @@ func ExampleDial_basic() {
4647
// You now have access to the proxied remote port in `conn`.
4748
}
4849

49-
// nolint:gocognit
50+
// nolint:gocognit,gocyclo
5051
func TestDial(t *testing.T) {
5152
t.Run("Ping", func(t *testing.T) {
5253
connectAddr, listenAddr := createDumbBroker(t)
@@ -229,6 +230,28 @@ func TestDial(t *testing.T) {
229230
return
230231
}
231232
})
233+
234+
t.Run("Closed", func(t *testing.T) {
235+
connectAddr, listenAddr := createDumbBroker(t)
236+
_, err := Listen(context.Background(), listenAddr)
237+
if err != nil {
238+
t.Error(err)
239+
return
240+
}
241+
dialer, err := DialWebsocket(context.Background(), connectAddr, nil)
242+
if err != nil {
243+
t.Error(err)
244+
return
245+
}
246+
go func() {
247+
_ = dialer.Close()
248+
}()
249+
select {
250+
case <-dialer.Closed():
251+
case <-time.NewTimer(time.Second).C:
252+
t.Error("didn't close in time")
253+
}
254+
})
232255
}
233256

234257
func BenchmarkThroughput(b *testing.B) {

0 commit comments

Comments
 (0)