Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Videoconferencing with webrtc + node.js

first sorry for my bad english. I'm trying to make a video call with WebRTC but it doesn't work. I'm using node.js+socket.io+express for the server. I appreciate any help or suggestions you can give me. Thank you very much. This is my code.

SERVER

var express = require('express')
  , io = require('socket.io')
  , app = express()
  , server = require('http').createServer(app)
  , io = io.listen(server);

server.listen(8080);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

var usuarios = [];

io.sockets.on('connection', function (socket) {
    usuarios.push(socket);
    console.log('Nuevo usuario conectado - ' + usuarios.length + ' en total');

    socket.on('message', function (mensaje) { 
        usuarios.forEach(function (usuario) {
            if (usuario != socket) {
                usuario.send(mensaje);
            }
        });
    });

    socket.on('disconnect', function () { 
        console.log("Usuario desconectado");
        // ...
    });
});

CLIENT

<html>
    <head>
        <title>Cliente</title>
    </head>
    <body>
        <video id='videolocal' autoplay style='width: 200px; height: 150px; border: 1px solid black;'></video>
        <video id='videoremoto' autoplay style='width: 200px; height: 150px; border: 1px solid black;'></video>
        <button type="button" onclick="iniciarCamara();">Iniciar Camara</button>
        <button type="button" onclick="pararCamara();">Parar Camara</button>
        <button type="button" onclick="conectar();">Conectar</button>
        <button type="button" onclick="desconectar();">Desconectar</button>

        <script src="/socket.io/socket.io.js"></script>
        <script>
            var socket = io.connect('http://localhost:8080');
            var videolocal = document.getElementById('videolocal');
            var videoremoto = document.getElementById('videoremoto');
            var streamlocal = null;
            var pc = null;
            var conectado = false;
            window.URL = window.URL || window.webkitURL;
            navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

            socket.on('message', function (mensaje) {
                var msg = JSON.parse(mensaje);

                if (msg.type === 'oferta') {
                    pc.setRemoteDescription(pc.SDP_OFFER, new SessionDescription(msg.sdp));
                    responder();
                } else if (msg.type === 'respuesta' && conectado) {
                    pc.setRemoteDescription(pc.SDP_ANSWER, new SessionDescription(msg.sdp));
                } else if (msg.type === 'candidate' && conectado) {
                    var candidate = new IceCandidate(msg.label, msg.candidate);
                    pc.processIceMessage(candidate);
                } else if (msg.type === 'desconectar' && conectado) {
                    //...
                }
            });

            function responder() {
                var oferta = pc.remoteDescription;
                var respuesta = pc.createAnswer(oferta.toSdp(), {has_audio:true, has_video:true});
                pc.setLocalDescription(pc.SDP_ANSWER, respuesta);
                socket.send({type: 'respuesta', sdp: respuesta.toSdp()});
                pc.startIce();
            }

            function crearPeerConnection() {
                pc = new webkitPeerConnection00(null, iceCallback);
                pc.addEventListener("addstream", anadirStreamRemoto, false);
                pc.addEventListener("removestream", eliminarStreamRemoto, false);

                function anadirStreamRemoto(event) {
                    videoremoto.src = window.webkitURL.createObjectURL(event.stream);
                }

                function eliminarStreamRemoto(event) {
                    videoremoto.src = "";
                }
            }

            function iniciarCamara() {
                navigator.getUserMedia({video: true, audio: true}, okCallback, errorCallback);

                function okCallback(stream) {
                    videolocal.src = window.URL.createObjectURL(stream);
                    streamlocal = stream;
                }

                function errorCallback(error) {
                    alert("Error");
                    return;
                }
            }

            function pararCamara() {
                videolocal.src = "";
            }

            function iceCallback(candidate, bMore) {
                if(candidate) {
                    socket.send({type: 'candidate', label: candidate.label, candidate: candidate.toSdp()});
                }
            }

            function conectar() {
                if (!conectado && streamlocal) {
                    crearPeerConnection();
                    conectado = true;
                    var oferta = pc.createOffer({has_audio:true, has_video:true});
                    pc.setLocalDescription(pc.SDP_OFFER, oferta);
                    socket.send({type: 'oferta', sdp: oferta.toSdp()});
                    pc.startIce();
                } else {
                    alert("No se ha iniciado el stream local");
                }
            }

            function desconectar() {
                pc.close();
                pc = null;
                conectado = false;
            }

    </script>
</body>

ERROR

Uncaught SyntaxError: Unexpected token o localhost:25
(anonymous function) localhost:25
EventEmitter.emit socket.io.js:633
SocketNamespace.onPacket socket.io.js:2239
Socket.onPacket socket.io.js:1930
Transport.onPacket socket.io.js:1332
Transport.onData socket.io.js:1303
websocket.onmessage

Regards.

like image 629
user1735617 Avatar asked Nov 03 '22 14:11

user1735617


1 Answers

You have to send jsObjects while the socket.io method .send() sends messages, to serve data you need to use .emit() method, so you have to replace all

socket.send({...});

with:

socket.emit('message', {...})

and so you have to remove this line:

var msg = JSON.parse(mensaje);
like image 161
frx08 Avatar answered Nov 09 '22 03:11

frx08