我愿意使用Socket.io和Simple-Peer建立一对一的视频聊天室,并且我使用socket.io室来实现一对一的算法。但是它不起作用,所以我很困惑。在此之前,我有一种算法,该算法没有房间,但仅适用于2个人,并且如果第三个人尝试连接他/他正在获得“等待”消息。在我当前的算法中,房间的“名称”是数字。如果房间中只有一个用户,则它正在发出特殊事件,当第二个连接房间的“名称”增加时,第三个用户进入“ 2”个房间并...。 这是我的代码:
服务器端:
vchns.on('connection', async function(socket){
try{
let room = vnumb;
socket.join(room);
socket.current_vroom = room
vchns.in(room).clients((err,clients)=>{
if(err) console.log(err);
if(clients.length < 2){
if(clients.length == 1){
socket.emit('CreatePeer')
}
}
if(clients.length >= 2){
++vnumb
}
})
socket.on('Offer', SendOffer);
socket.on('Answer', SendAnswer);
function SendOffer(offer){
socket.broadcast.in(socket.current_vroom).emit('BackOffer', offer);
}
function SendAnswer(data){
socket.broadcast.in(socket.current_vroom).emit('BackAnswer', data);
}
}catch(err){
console.log(err.message)
}
})
客户端:
let client = {}
navigator.mediaDevices.getUserMedia({video: true, audio: true})
.then(stream=>{
localVideo.srcObject = stream;
localVideo.play();
function initPeer(type){
let peer = new Peer({initiator: (type == 'init')? true : false, stream: stream, trickle: false});
peer.on('stream', (stream)=>{
CreateVideo(stream)
})
return peer;
}
function MakePeer(){
client.gotAnswer = false;
let peer = initPeer('init');
peer.on('signal', function(data){
if(!client.gotAnswer){
socket.emit('Offer', data)
}
})
client.peer = peer
}
function FrontAnswer(offer){
let peer = initPeer('notInit');
peer.on('signal', (data)=>{
socket.emit('Answer', data);
})
peer.signal(offer)
}
function SignalAnswer(answer){
client.gotAnswer = true;
let peer = client.peer;
peer.signal(answer)
}
function CreateVideo(stream){
let video = document.createElement('video');
video.id = 'remoteVideo';
video.srcObject = stream;
document.querySelector('#remoteVideoDiv').appendChild(video);
video.play()
}
socket.on('BackOffer', FrontAnswer)
socket.on('BackAnswer', SignalAnswer);
socket.on('CreatePeer', MakePeer)
})
.catch(err=>{
console.log(err.message)
})
那怎么了?
谢谢!