我正在使用ReactJS上的WebRTC进行视频通话+聊天应用程序。尝试在2个对等体之间发送消息时出现此错误
无法在'RTCDataChannel'上执行'发送':RTCDataChannel.readyState不是'打开'
我想这取决于我如何设置对等连接和dataChannel。以下是我设置dataChannel的方法:
componentWillMount() {
this.initial();
}
send(message) {
if (connectedUser) {
message.name = connectedUser;
}
conn.send(JSON.stringify(message));
}
initial() {
navigator.getUserMedia({video: true, audio: true}, (myStream) => {
stream = myStream;
this.setState({localVideoSrc: window.URL.createObjectURL(stream)});
var configuration = {
"iceServers": [{ "url": "stun:stun2.1.google.com:19302" }]
};
yourConn = new RTCPeerConnection(configuration, {optional: [{RtpDataChannels: true}]});
yourConn.addStream(stream);
yourConn.onaddstream = (e) => {
this.setState({remoteVideoSrc: window.URL.createObjectURL(e.stream)});
};
this.send({
type: "update"
});
yourConn.onicecandidate = (event) => {
if (event.candidate) {
this.send({
type: "candidate",
candidate: event.candidate
});
}
};
dataChannel = yourConn.createDataChannel("channel1", {reliable:true});
console.log("dataChannel:", dataChannel);
dataChannel.onerror = (error) => {
console.log("Ooops...error:", error);
};
//when we receive a message from the other peer, display it on the screen
dataChannel.onmessage = (event) => {
var oldMessages = this.state.receivedMessage;
var userB = this.state.callToUser;
this.setState({
receivedMessage: oldMessages + userB + ": " + event.data + "<br />"
})
};
dataChannel.onclose = () => {
console.log("data channel is closed");
};
}, (error) => {
console.log(error);
});
}
请帮我解决这个问题。非常感谢!
更新: 1. yourConn
是一个变量,我在我的组件顶部声明为:var yourConn
变量conn
是从另一个文件导入的。这是文件
export var conn = new WebSocket('ws:// localhost:9090');
conn.onopen =()=&gt; { console.log('连接到信令服务器'); }; conn.onerror =(err)=&gt; { console.log(“得到错误”,错误); }; conn.onmessage =(msg)=&gt; { if(msg.data ===“Hello world”){ console.log(“收到消息”,msg.data); } };