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.

feat: Add Closed func to Dialer #381

Merged
merged 3 commits into from
Jul 9, 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
15 changes: 15 additions & 0 deletions wsnet/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func Dial(conn net.Conn, iceServers []webrtc.ICEServer) (*Dialer, error) {
conn: conn,
ctrl: ctrl,
rtc: rtc,
closedChan: make(chan struct{}),
connClosers: make([]io.Closer, 0),
}

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

closedChan chan struct{}
connClosers []io.Closer
connClosersMut sync.Mutex
}
Expand Down Expand Up @@ -136,6 +138,13 @@ func (d *Dialer) negotiate() (err error) {
_ = connCloser.Close()
}
d.connClosers = make([]io.Closer, 0)

select {
case <-d.closedChan:
return
default:
}
close(d.closedChan)
})
}()

Expand Down Expand Up @@ -184,6 +193,12 @@ func (d *Dialer) negotiate() (err error) {
return <-errCh
}

// Closed returns a channel that closes when
// the connection is closed.
func (d *Dialer) Closed() <-chan struct{} {
return d.closedChan
}

// Close closes the RTC connection.
// All data channels dialed will be closed.
func (d *Dialer) Close() error {
Expand Down
25 changes: 24 additions & 1 deletion wsnet/dial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net"
"strconv"
"testing"
"time"

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

// nolint:gocognit
// nolint:gocognit,gocyclo
func TestDial(t *testing.T) {
t.Run("Ping", func(t *testing.T) {
connectAddr, listenAddr := createDumbBroker(t)
Expand Down Expand Up @@ -229,6 +230,28 @@ func TestDial(t *testing.T) {
return
}
})

t.Run("Closed", func(t *testing.T) {
connectAddr, listenAddr := createDumbBroker(t)
_, err := Listen(context.Background(), listenAddr)
if err != nil {
t.Error(err)
return
}
dialer, err := DialWebsocket(context.Background(), connectAddr, nil)
if err != nil {
t.Error(err)
return
}
go func() {
_ = dialer.Close()
}()
select {
case <-dialer.Closed():
case <-time.NewTimer(time.Second).C:
t.Error("didn't close in time")
}
})
}

func BenchmarkThroughput(b *testing.B) {
Expand Down