AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
[TOC] ## 创建数据通道 发送方 ``` const peerConnection = new RTCPeerConnection(configuration); const dataChannel = peerConnection.createDataChannel(); ``` 接收方 ``` const peerConnection = new RTCPeerConnection(configuration); peerConnection.addEventListener('datachannel', event => { const dataChannel = event.channel; }); ``` ## 打开和关闭事件 ``` const messageBox = document.querySelector('#messageBox'); const sendButton = document.querySelector('#sendButton'); const peerConnection = new RTCPeerConnection(configuration); const dataChannel = peerConnection.createDataChannel(); // Enable textarea and button when opened dataChannel.addEventListener('open', event => { messageBox.disabled = false; messageBox.focus(); sendButton.disabled = false; }); // Disable input when closed dataChannel.addEventListener('close', event => { messageBox.disabled = false; sendButton.disabled = false; }); ``` ## 留言内容 `send()`函数的`data`参数可以是字符串,`Blob`,`ArrayBuffer`或and`ArrayBufferView` 发送方 ``` const messageBox = document.querySelector('#messageBox'); const sendButton = document.querySelector('#sendButton'); // Send a simple text message when we click the button sendButton.addEventListener('click', event => { const message = messageBox.textContent; dataChannel.send(message); }) ``` 接收方 ``` const incomingMessages = document.querySelector('#incomingMessages'); const peerConnection = new RTCPeerConnection(configuration); const dataChannel = peerConnection.createDataChannel(); // Append new messages to the box of incoming messages dataChannel.addEventListener('message', event => { const message = event.data; incomingMessages.textContent += message + '\n'; }); ```