forked from pion/webrtc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datachannel_js_detach.go
71 lines (55 loc) · 1.33 KB
/
datachannel_js_detach.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
// +build js,wasm
package webrtc
import (
"errors"
)
type detachedDataChannel struct {
dc *DataChannel
read chan DataChannelMessage
done chan struct{}
}
func newDetachedDataChannel(dc *DataChannel) *detachedDataChannel {
read := make(chan DataChannelMessage)
done := make(chan struct{})
// Wire up callbacks
dc.OnMessage(func(msg DataChannelMessage) {
read <- msg // pion/webrtc/projects/15
})
// pion/webrtc/projects/15
return &detachedDataChannel{
dc: dc,
read: read,
done: done,
}
}
func (c *detachedDataChannel) Read(p []byte) (int, error) {
n, _, err := c.ReadDataChannel(p)
return n, err
}
func (c *detachedDataChannel) ReadDataChannel(p []byte) (int, bool, error) {
select {
case <-c.done:
return 0, false, errors.New("Reader closed")
case msg := <-c.read:
n := copy(p, msg.Data)
if n < len(msg.Data) {
return n, msg.IsString, errors.New("Read buffer to small")
}
return n, msg.IsString, nil
}
}
func (c *detachedDataChannel) Write(p []byte) (n int, err error) {
return c.WriteDataChannel(p, false)
}
func (c *detachedDataChannel) WriteDataChannel(p []byte, isString bool) (n int, err error) {
if isString {
err = c.dc.SendText(string(p))
return len(p), err
}
err = c.dc.Send(p)
return len(p), err
}
func (c *detachedDataChannel) Close() error {
close(c.done)
return c.dc.Close()
}