github.com/pion/webrtc/v3@v3.2.24/datachannel_js_detach.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 //go:build js && wasm 5 // +build js,wasm 6 7 package webrtc 8 9 import ( 10 "errors" 11 ) 12 13 type detachedDataChannel struct { 14 dc *DataChannel 15 16 read chan DataChannelMessage 17 done chan struct{} 18 } 19 20 func newDetachedDataChannel(dc *DataChannel) *detachedDataChannel { 21 read := make(chan DataChannelMessage) 22 done := make(chan struct{}) 23 24 // Wire up callbacks 25 dc.OnMessage(func(msg DataChannelMessage) { 26 read <- msg // pion/webrtc/projects/15 27 }) 28 29 // pion/webrtc/projects/15 30 31 return &detachedDataChannel{ 32 dc: dc, 33 read: read, 34 done: done, 35 } 36 } 37 38 func (c *detachedDataChannel) Read(p []byte) (int, error) { 39 n, _, err := c.ReadDataChannel(p) 40 return n, err 41 } 42 43 func (c *detachedDataChannel) ReadDataChannel(p []byte) (int, bool, error) { 44 select { 45 case <-c.done: 46 return 0, false, errors.New("Reader closed") 47 case msg := <-c.read: 48 n := copy(p, msg.Data) 49 if n < len(msg.Data) { 50 return n, msg.IsString, errors.New("Read buffer to small") 51 } 52 return n, msg.IsString, nil 53 } 54 } 55 56 func (c *detachedDataChannel) Write(p []byte) (n int, err error) { 57 return c.WriteDataChannel(p, false) 58 } 59 60 func (c *detachedDataChannel) WriteDataChannel(p []byte, isString bool) (n int, err error) { 61 if isString { 62 err = c.dc.SendText(string(p)) 63 return len(p), err 64 } 65 66 err = c.dc.Send(p) 67 68 return len(p), err 69 } 70 71 func (c *detachedDataChannel) Close() error { 72 close(c.done) 73 74 return c.dc.Close() 75 }