Я использую экспресс в верхней части node.js для сигнализации для моего проекта WebRTC.
В настоящее время до даты оба удаленных видеопотока вообще ничего не отображают, и я не уверен, какая часть моего кода может быть причиной этого.
В приложении есть журналы, которые вышливызывающего и вызываемого абонента, который я могу проверить, что и createOffer, и createAnswer сработали (у меня также был файл console.log, чтобы проверить, срабатывает ли .ontrack, и я могу подтвердить, что это происходит, но не видно на рисунках).
Сторона вызывающего абонента Сторона вызываемого абонента
У меня есть код в репозитории в GitHub (https://github.com/tngrj/chatter)
Сигнальный код
'use strict';
var express = require('express');
var app = (module.exports.app = express());
var server = require('http').createServer(app);
var io = require('socket.io')(server);
const PORT_NO = process.env.APP_PORT || 3000;
server.listen(PORT_NO);
app.use(express.static('.'));
io.on('connection', socket => {
function log() {
const array = ['Message from server:'];
for (let i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
socket.on('message', message => {
log('Got message:', message);
socket.broadcast.emit('message', message);
});
socket.on('create or join', room => {
var clientsInRoom = io.nsps['/'].adapter.rooms[room];
var numClients =
clientsInRoom === undefined ? 0 : Object.keys(clientsInRoom);
var numClients =
clientsInRoom === undefined
? 0
: Object.keys(clientsInRoom.sockets).length;
// max two clients
if (numClients === 2) {
socket.emit('full', room);
return;
}
log('Room ' + room + ' now has ' + (numClients + 1) + ' client(s)');
if (numClients === 0) {
socket.join(room);
log('Client ID ' + socket.id + ' created room ' + room);
socket.emit('created', room, socket.id);
} else {
log('Client ID ' + socket.id + ' joined room ' + room);
io.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room, socket.id);
io.in(room).emit('ready');
}
});
});
Основной код
'use strict';
var isInitiator;
var configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
};
var pc = new RTCPeerConnection(configuration);
// Define action buttons.
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
/////////////////////////////////////////////
window.room = prompt('Enter room name:');
var socket = io.connect();
if (room !== '') {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
isInitiator = true;
startVideo();
});
socket.on('full', function(room) {
console.log('Message from client: Room ' + room + ' is full :^(');
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
callButton.disabled = true;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
async function sendMessage(message) {
console.log('Client sending message: ', message);
await socket.emit('message', message);
}
// This client receives a message
socket.on('message', async function(message) {
try {
if (message.type === 'offer') {
await pc.setRemoteDescription(new RTCSessionDescription(message));
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
video: true
});
stream.getTracks().forEach(track => pc.addTrack(track, stream));
createPeerConnection();
await pc
.setLocalDescription(await pc.createAnswer())
.then(function() {
sendMessage(pc.localDescription);
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
} else if (message.type === 'answer') {
await pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate') {
await pc.addIceCandidate(candidate);
}
} catch (err) {
console.error(err);
}
});
////////////////////////////////////////////////////
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
// Set up initial action buttons status: disable call and hangup.
callButton.disabled = true;
hangupButton.disabled = true;
// Add click event handlers for buttons.
callButton.addEventListener('click', callStart);
hangupButton.addEventListener('click', hangupCall);
function startVideo() {
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(function(stream) {
localVideo.srcObject = stream;
stream.getTracks().forEach(track => pc.addTrack(track, stream));
})
.catch(function(err) {
console.log('getUserMedia() error: ' + err.name);
});
callButton.disabled = false;
}
async function callStart() {
createPeerConnection();
callButton.disabled = true;
hangupButton.disabled = false;
if (isInitiator) {
console.log('Sending offer to peer');
await pc
.setLocalDescription(await pc.createOffer())
.then(function() {
sendMessage(pc.localDescription);
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
}
}
/////////////////////////////////////////////////////////
function createPeerConnection() {
try {
pc.ontrack = event => {
if (remoteVideo.srcObject) return;
remoteVideo.srcObject = event.streams[0];
};
pc.onicecandidate = ({ candidate }) => sendMessage({ candidate });
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function hangupCall() {
pc.close();
pc = null;
console.log('Call Ended');
}