Files
go-webrtc-net/listener.go

70 lines
1.1 KiB
Go
Raw Normal View History

2025-02-06 22:50:09 -05:00
package webrtc
import (
"context"
"net"
"github.com/pion/webrtc/v3"
)
// Listen creates a new WebRTC listener using the provided net.Listener for signaling
func Listen(lstn net.Listener) (net.Listener, error) {
ctx, cancel := context.WithCancel(context.Background())
2025-02-07 15:25:50 -05:00
l := &RTCListener{
2025-02-06 22:50:09 -05:00
underlying: lstn,
config: &webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
2025-02-07 15:25:50 -05:00
{URLs: STUN_SERVER_URLS},
2025-02-06 22:50:09 -05:00
},
},
acceptChan: make(chan net.Conn),
ctx: ctx,
cancel: cancel,
}
go l.acceptLoop()
return l, nil
}
2025-02-07 15:25:50 -05:00
func (l *RTCListener) Accept() (net.Conn, error) {
2025-02-06 22:50:09 -05:00
select {
case conn := <-l.acceptChan:
return conn, nil
case <-l.ctx.Done():
return nil, ErrConnectionClosed
}
}
2025-02-07 15:25:50 -05:00
func (l *RTCListener) Close() error {
2025-02-06 22:50:09 -05:00
l.mu.Lock()
defer l.mu.Unlock()
if l.closed {
return nil
}
l.closed = true
l.cancel()
return l.underlying.Close()
}
2025-02-07 15:25:50 -05:00
func (l *RTCListener) Addr() net.Addr {
2025-02-06 22:50:09 -05:00
return l.underlying.Addr()
}
2025-02-07 15:25:50 -05:00
func (l *RTCListener) acceptLoop() {
2025-02-06 22:50:09 -05:00
for {
conn, err := l.underlying.Accept()
if err != nil {
l.Close()
return
}
select {
case l.acceptChan <- conn:
case <-l.ctx.Done():
return
}
}
}