Skip to content

Commit

Permalink
Add OnOfferConnected channel for synchronize connected event for client
Browse files Browse the repository at this point in the history
Signed-off-by: billfort <[email protected]>
  • Loading branch information
billfort committed May 9, 2024
1 parent bbd586f commit 3f52651
Showing 1 changed file with 27 additions and 11 deletions.
38 changes: 27 additions & 11 deletions api/webrtc/webrtc.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,13 @@ type DataChannelMessage struct {
}

type Peer struct {
pc *webrtc.PeerConnection
dc *webrtc.DataChannel
offer string
answer string
OnSdp chan string
OnMessage chan DataChannelMessage
pc *webrtc.PeerConnection
dc *webrtc.DataChannel
offer string
answer string
OnSdp chan string
OnMessage chan DataChannelMessage
OnOfferConnected chan struct{}

mutex sync.RWMutex
isConnected bool
Expand All @@ -54,9 +55,10 @@ type Peer struct {

func NewPeer(urls []string) *Peer {
p := &Peer{
OnSdp: make(chan string, 1),
isConnected: false,
OnMessage: make(chan DataChannelMessage, 128),
OnSdp: make(chan string, 1),
isConnected: false,
OnMessage: make(chan DataChannelMessage, 128),
OnOfferConnected: make(chan struct{}, 1),
}

config := webrtc.Configuration{
Expand Down Expand Up @@ -91,16 +93,24 @@ func (c *Peer) Offer(label string) error {
return
}
c.offer = encodedDescr
c.OnSdp <- encodedDescr
select {
case c.OnSdp <- encodedDescr:
default:
}
}
})

dc, err := c.pc.CreateDataChannel(label, nil)
if err != nil {
return err
}

dc.OnOpen(func() {
log.Debugf("Data channel %v has been opened\n", dc.Label())
select {
case c.OnOfferConnected <- struct{}{}:
default:
}
c.mutex.Lock()
defer c.mutex.Unlock()
c.isConnected = true
Expand Down Expand Up @@ -186,7 +196,10 @@ func (c *Peer) Answer(offerSdp string) error {
return
}
c.answer = encodedDescr
c.OnSdp <- encodedDescr
select {
case c.OnSdp <- encodedDescr:
default:
}
}
})

Expand Down Expand Up @@ -362,6 +375,9 @@ func (c *Peer) SetReadLimit(l int64) {
}

func (c *Peer) Close() error {
close(c.OnSdp)
close(c.OnMessage)
close(c.OnOfferConnected)
if c.dc != nil {
if err := c.dc.Close(); err != nil {
return err
Expand Down

0 comments on commit 3f52651

Please sign in to comment.