p2p 通话技术 打电话 打视频 占用性能
onmessage(e) {
const json = JSON.parse(e.data);
const description = json.message;
toUserId = json.userId;
switch (description.type) {
case "connect":
if (confirm(toUserId + "请求连接!")) { ,
//准备连接
this.startHandle().then(() => {
socket.send(
JSON.stringify({
userId: userId,
toUserId: toUserId,
message: { type: "start" },
})
);
});
}
break;
case "start":
//同意连接之后开始连接
this.startConnection();
break;
case "offer":
peerConnection
.setRemoteDescription(new RTCSessionDescription(description))
.then(() => {})
.catch((err) => {
console.log("local 设置远端描述信息错误", err);
});
peerConnection
.createAnswer()
.then(function (answer) {
peerConnection
.setLocalDescription(answer)
.then(() => {
console.log("设置本地answer成功!");
})
.catch((err) => {
console.error("设置本地answer失败", err);
});
socket.send(
JSON.stringify({
userId: userId,
toUserId: toUserId,
message: answer,
})
);
})
.catch((e) => {
console.error(e);
});
break;
case "icecandidate":
// 创建 RTCIceCandidate 对象
let newIceCandidate = new RTCIceCandidate(description.icecandidate);
// 将本地获得的 Candidate 添加到远端的 RTCPeerConnection 对象中
peerConnection
.addIceCandidate(newIceCandidate)
.then(() => {
console.log(`addIceCandidate 成功`);
})
.catch((error) => {
console.log(`addIceCandidate 错误:\n` + `${error.toString()}.`);
});
break;
case "answer":
peerConnection
.setRemoteDescription(new RTCSessionDescription(description))
.then(() => {
console.log("设置remote answer成功!");
})
.catch((err) => {
console.log("设置remote answer错误", err);
});
break;
default:
break;
}
},
加班万岁!