简体   繁体   中英

WebRTC video chat

I am trying to build a 1-to-1 video chat with webrtc and the RTCPeerConnection API. A problem with my code is that after an initial user connects to the server, it doesn't receive messages from the server when other users emit messages via socket.io. The clients only receive their own emitted messages. Here is some of my code. The full project is on Github at: https://github.com/rashadrussell/webrtc_experiment

Client-Side

var isInitiator = false;


socket.on('initiatorFound', function(data) {
    isInitiator = data.setInitiator;
    console.log("Is Initiator? " + isInitiator);
});


navigator.getMedia = (
        navigator.getUserMedia ||
        navigator.webkitGetUserMedia ||
        navigator.mozGetUserMedia ||
        navigator.msGetUserMedia
    );

navigator.getMedia(
    {video: true, audio: false},
    function(stream) {
        var video = document.getElementById("localView");
        video.src = window.URL.createObjectURL(stream);
        console.log("Add Stream");
        sendMessage('streamAdd', {streamAdded: 'stream-added'});

        createPeerConnection();
        pc.addStream(stream);

        if(isInitiator)
        {
            callPeer();
        }

    },
    function(err) {
        console.log("The following error occured: ");
        console.dir(err);
    }

);


function sendMessage(type, message)
{
    console.log("Sending Message");
    socket.emit('message',{
        "type": type,
        "message": message
    });
}

function createPeerConnection() {

    pc = new rtcPeerConnection(servers, options);
    console.dir(pc);

    pc.onicecandidate = function(evt) {
        if(evt.candidate == null) return; 
        pc.onicecandidate = null;           

        console.log("Send Ice Candidate");
        sendMessage("iceCandidate", JSON.stringify(evt.candidate));
    };

    pc.onaddstream = function(evt) {
        document.body.append("<video id='remoteVideo' autoplay></video>");
        var remoteVid = document.getElementById("remoteVideo");
        remoteVid.src = window.URL.createObjectURL(evt.stream);
    };

}


function callPeer() {

    pc.createOffer(function (offer) {
            pc.setLocalDescription(offer, function() {
                sendMessage("offer", JSON.stringify(offer));
            });
            console.log("Send Offer");
        }, function(err) { console.log("Offer Error: " + err) },
            videoConstraints
        );

}

function answerPeer() {

    pc.createAnswer(function(answer) {
        pc.setLocalDescription(answer);
        sendMessage("answer", JSON.stringify(answer))
    }, function(err) { console.log("Sending Answer Error: " + err) },
        videoConstraints
    );

}

socket.on('message', function(message) {
    console.log("CONSOLE MESSAGE:");
    console.dir(message);

    if(message.type == 'streamAdd') {
        console.log('Stream was added');
        createPeerConnection();

        if(isInitiator) {
            callPeer();
        }

    } else if(message.type == 'offer') {

        pc.setRemoteDescription( new rtcSessionDescription(JSON.parse(message.message)));

        if(!isInitiator)
        {
            console.log("Sending Answer");
            answerPeer();
        }


    } else if(message.type == 'answer') {
        pc.setRemoteDescription( new rtcSessionDescription(JSON.parse(message.message)));
    } else if(message.type == 'iceCandidate') {
        console.log("Get Ice Candidate");
        pc.addIceCandidate(new rtcIceCandidate(JSON.parse(message.message)) );
    }

});

Server-Side

var isInitiator = false;
io.sockets.on('connection', function(socket) {

    if (!isInitiator) {
      isInitiator = true;
      socket.emit('initiatorFound', {setInitiator: isInitiator});
    } else {
      socket.emit('initiatorFound', {setInitiator: !isInitiator});
    }

    // Signaling Channel
    socket.on('message', function(message) {

      if (message.type == 'streamAdd') {
        console.log('Got message: ' + message);
      }
      //socket.emit('message' ,message);
      // Should be:
      socket.broadcast.emit('message', message);

    });

});

See if you want to send message to particular user you set unique ID(socket.id) but now you are try just testing correct so change your server side code

var isInitiator = false;

io.sockets.on('connection', function(socket) {

    if (!isInitiator) {
      isInitiator = true;
      socket.emit('initiatorFound', {setInitiator: isInitiator});
    } else {
      socket.emit('initiatorFound', {setInitiator: !isInitiator});
    }

    // Signaling Channel
    socket.on('message', function(message) {

      if (message.type == 'streamAdd') {
        console.log('Got message: ' + message);
      }
      socket.emit('message' ,message);

    });

});

see here socket.emit('message',message); this socket object contain your id so its send a message to you if you want do send a message to particular user you know the unique.id any way send message to every connection expect this socket(mean current socket)

io.sockets.on('connection', function(socket) {

    if (!isInitiator) {
      isInitiator = true;
      socket.emit('initiatorFound', {setInitiator: isInitiator});
    } else {
      socket.emit('initiatorFound', {setInitiator: !isInitiator});
    }

    // Signaling Channel
    socket.on('message', function(message) {

      if (message.type == 'streamAdd') {
        console.log('Got message: ' + message);
      }
      socket.broadcast.emit('message' ,message);

    });

});

I figured out why the other clients weren't being notified when a message is emitted. In my server-side code, under the signaling channel section, socket.emit is supposed to be socket.broadcast.emit or io.sockets.emit.

Socket.emit only relays the message back to the client who initiated the call the server. socket.broadcast.emit relays the message to all clients except for the client who initiated the call, and io.sockets.emit relays the message to all clients including the client who initiated the call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM