最近在搞webrtc,在编写函数处理远端传递来的candidate时报错了,具体信息如下。国内关于webrtc的资料很少,所以去国外社区转了一圈,回来记录一下报错的解决方案
其实这个bug也好解决,根据报错信息可以判断是RTCIceCandidate
的sdpMid
和sdpMlineIndex
为null了,看了看RTCIceCandidate的原码,基本就能判断出应该是对端传递candidate的时候没传递这两个值
interface RTCIceCandidate {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/address) */
readonly address: string | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/candidate) */
readonly candidate: string;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/component) */
readonly component: RTCIceComponent | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/foundation) */
readonly foundation: string | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/port) */
readonly port: number | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/priority) */
readonly priority: number | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/protocol) */
readonly protocol: RTCIceProtocol | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/relatedAddress) */
readonly relatedAddress: string | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/relatedPort) */
readonly relatedPort: number | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/sdpMLineIndex) */
readonly sdpMLineIndex: number | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/sdpMid) */
readonly sdpMid: string | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/tcpType) */
readonly tcpType: RTCIceTcpCandidateType | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/type) */
readonly type: RTCIceCandidateType | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/usernameFragment) */
readonly usernameFragment: string | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCIceCandidate/toJSON) */
toJSON(): RTCIceCandidateInit;
}
于是我检查发送来的数据是这么构造的
我丢你的雷姆,这俩参数我压根就没传递。我们修改一下传递的json数据
tip:上述修改方式任然过于繁杂,const candidateJson = JSON.stringfy(event.candidate)即可实现预期效果
然后重启项目我们会发现报错消失了,并且也能显示出我们想要的效果,webrtc能够正常搭建
这篇文章提供了上面这个项目的源码(前端+后端)但还未整理,后续我会发布有关webrtc入门demo的文章和各位分享
webRTC详解文章
【前后端的那些事】2万字详解WebRTC(附加入门demo代码解析)