我想在2台设备上创建WebRTC连接。
在我的第一台设备(发起方)上,我使用以下方法创建商品:
createOffer() {
const { pc } = this;
pc.onnegotiationneeded = () => {
pc.createOffer()
.then(offer => pc.setLocalDescription(offer))
.then(() => {
this.setState({
offer: JSON.stringify(pc.localDescription)
});
});
};
}
然后在第二台设备(接收器)上,创建答案:
createAnswer() {
const { pc } = this;
const { dataOffer } = this.state;
if (dataOffer) {
const sd = new RTCSessionDescription(JSON.parse(dataOffer));
pc.setRemoteDescription(sd)
.then(() => pc.createAnswer())
.then(answer => {
this.setState({
offer: JSON.stringify(answer)
});
return pc.setLocalDescription(answer);
});
}
}
但是,在第一个设备上发送Answer后,我遇到了这个错误:PeerConnection cannot create an answer in a state other than have-remote-offer or have-local-pranswer.
启动器收到答案后,我用答案数据运行createAnswer
方法,这可能是问题所在吗?
收到答案后我真的不明白我需要使用哪种方法/事件:/
使用启动器设备的新方法进行编辑:
receiveAnswer() {
const { pc } = this;
const { dataOffer } = this.state;
const sd = new RTCSessionDescription(JSON.parse(dataOffer));
pc.setRemoteDescription(sd);
}
但是连接状态停留在checking
上:(
您可以看到我的componentDidMount
:
componentDidMount() {
const { pc } = this;
pc.oniceconnectionstatechange = () => {
this.setState({
connectionState: pc.iceConnectionState
});
};
pc.onaddstream = ({ stream }) => {
if (stream) {
this.setState({
receiverVideoURL: stream.toURL()
});
}
};
}