RTCDataChannel.send() - Web APIs 编辑
The send()
method of the RTCDataChannel
interface sends data across the data channel to the remote peer. This can be done any time except during the initial process of creating the underlying transport channel. Data sent before connecting is buffered if possible (or an error occurs if it's not possible), and is also buffered if sent while the connection is closing or closed.
Different browsers have different limitations on the size of the message you can send. Specifications exist to define how to automatically fragment large messages, but not all browsers implement them, and those that do have various additional restrictions. This will get less complicated over time, but for now, if you have questions, see Understanding message size limits in Using WebRTC data channels.
Syntax
RTCDataChannel.send(data);
Parameters
data
- The data to transmit across the connection. This may be a
USVString
, aBlob
, anArrayBuffer
, or anArrayBufferView
.
Return value
undefined
.
Exceptions
InvalidStateError
- Since the data channel uses a separate transport channel from the media content, it must establish its own connection; if it hasn't finished doing so (that is, its
readyState
is"connecting")
, this error occurs without sending or buffering thedata
. NetworkError
- The specified
data
would need to be buffered, and there isn't room for it in the buffer. In this scenario, the underlying transport is immediately closed. TypeError
- The specified
data
is too large for the other peer to receive. Since there are multiple techniques for breaking up large data into smaller pieces for transfer, it's possible to encounter scenarios in which the other peer does not support the same ones. For example, if one peer is a modern browser that supports using theEOR
(End of Record) flag to indicate when a received message is the last piece of a multi-part object sent usingsend()
. For more information about message size restrictions, see Understanding message size limits in Using WebRTC data channels.
Example
In this example, a routine called sendMessage()
is created; it accepts an object as input and sends to the remote peer, over the RTCDataChannel
, a JSON string with the specified object and a time stamp.
var pc = new RTCPeerConnection();
var dc = pc.createDataChannel("BackChannel");
function sendMessage(msg) {
let obj = {
"message": msg,
"timestamp": new Date()
}
dc.send(JSON.stringify(obj));
}
Specifications
Specification | Status | Comment |
---|---|---|
WebRTC 1.0: Real-time Communication Between Browsers The definition of 'RTCDataChannel.send()' in that specification. | Candidate Recommendation | Initial specification. |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论