-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebrtcDataChannelState.go
83 lines (80 loc) · 2.07 KB
/
webrtcDataChannelState.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"github.com/pion/webrtc/v3"
)
type WebRTCDataChannelStates struct {
DataChannels map[uint16]*webrtc.DataChannel
MessageCh chan WebRTCDataChannelMessage
}
type WebRTCDataChannelMessage struct {
ID uint16
Message webrtc.DataChannelMessage
Error error
}
type ReceivedDataChannelMessage struct {
UserName string
ID uint16
Message webrtc.DataChannelMessage
}
func (dc *WebRTCDataChannelStates) SendMessage(message ReceivedDataChannelMessage) {
for i, channel := range dc.DataChannels {
if i == message.ID {
channel.Send(message.Message.Data)
}
}
}
func (dc *WebRTCDataChannelStates) Close() {
for _, v := range dc.DataChannels {
v.Close()
}
close(dc.MessageCh)
}
func NewWebRTCDataChannelStates(peerConnection *webrtc.PeerConnection) (*WebRTCDataChannelStates, error) {
dc := &WebRTCDataChannelStates{
DataChannels: make(map[uint16]*webrtc.DataChannel),
MessageCh: make(chan WebRTCDataChannelMessage),
}
err := addWebRTCDataChannel("sample", 20, peerConnection, dc)
if err != nil {
return nil, err
}
err = addWebRTCDataChannel("sample2", 21, peerConnection, dc)
if err != nil {
return nil, err
}
return dc, nil
}
func addWebRTCDataChannel(label string, id uint16, peerConnection *webrtc.PeerConnection,
dc *WebRTCDataChannelStates) error {
dataChannel, err := newWebRTCDataChannel(label, id, peerConnection)
if err != nil {
return err
}
dc.DataChannels[*dataChannel.ID()] = dataChannel
dataChannel.OnMessage(func(msg webrtc.DataChannelMessage) {
dc.MessageCh <- WebRTCDataChannelMessage{
ID: id,
Message: msg,
}
})
dataChannel.OnError(func(err error) {
dc.MessageCh <- WebRTCDataChannelMessage{
ID: id,
Error: err,
}
})
return nil
}
func newWebRTCDataChannel(label string, id uint16, peerConnection *webrtc.PeerConnection) (*webrtc.DataChannel, error) {
negotiated := true
ordered := false
dc, err := peerConnection.CreateDataChannel(label, &webrtc.DataChannelInit{
ID: &id,
Negotiated: &negotiated,
Ordered: &ordered,
})
if err != nil {
return nil, err
}
return dc, nil
}