简体   繁体   English

WebRTC:向简单的 WebRTC 和 WebSocket 应用程序添加房间 - 需要建议

[英]WebRTC: Add rooms to simple WebRTC & WebSocket app - Advice Needed

I am very new to webrtc and coding, so apologies if this is not a clear question.我对webrtc和编码很webrtc ,所以如果这不是一个明确的问题,我很抱歉。

I have followed the Shane Tully example here and amended it to run on my AWS server.我遵循了此处的 Shane Tully 示例并将其修改为在我的 AWS 服务器上运行。 Its running find but it only allows me one connection at a time.它正在运行 find 但它一次只允许我建立一个连接。 I would like to have users enter my URL followed by a room name in order to connect to a room.我想让用户输入我的 URL 后跟一个房间名称,以便连接到一个房间。

eg www.myurl.com/apple where apple is the room that will be created.例如 www.myurl.com/apple 其中 apple 是将要创建的房间。 Here is an example - if you add /apppl at the end of this URL it will create a room.这是一个示例 - 如果您在此 URL 的末尾添加 /apppl,它将创建一个房间。 (The code for this example is rather complex and uses socket.io . where I use ws for Node to create the websockets) (此示例的代码相当复杂并使用socket.io 。我使用 ws 为 Node 创建 websockets)

Does anyone have any advice on this?有没有人对此有任何建议? My overall aim is to create an Android App which incorporates video calling functionality, and uses WebView to display the calling feature, which is why I need different URLs for each pair of devices so they both access the same room.我的总体目标是创建一个包含视频通话功能的 Android 应用程序,并使用 WebView 来显示通话功能,这就是为什么我需要为每对设备使用不同的 URL,以便它们都可以访问同一个房间。

Thank you in advance!提前谢谢你! Claire克莱尔

Server Code:服务器代码:

const HTTPS_PORT = 443;
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;

const serverConfig = {
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem'),
};

// ----------------------------------------------------------------------------------------

// Create a server for the client html page
var handleRequest = function(request, response) {
    // Render the single client html file for any request the HTTP server receives
    console.log('request received: ' + request.url);

    if(request.url === '/') {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end(fs.readFileSync('client/index.html'));

    } else if(request.url === '/webrtc.js') {
        response.writeHead(200, {'Content-Type': 'application/javascript'});
        response.end(fs.readFileSync('client/webrtc.js'));
    }
};

var httpsServer = https.createServer(serverConfig, handleRequest);
httpsServer.listen(HTTPS_PORT, '0.0.0.0');

// ----------------------------------------------------------------------------------------

// Create a server for handling websocket calls
var wss = new WebSocketServer({server: httpsServer});

wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        // Broadcast any received message to all clients
        console.log('received: %s', message);
        wss.broadcast(message);
    });
});

wss.broadcast = function(data) {
    this.clients.forEach(function(client) {
        if(client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
};

console.log('Server running. Visit https://localhost:' + HTTPS_PORT + ' in Firefox/Chrome (note the HTTPS; there is no HTTP -> HTTPS redirect!)');
//console.log("TEST TEST TEST" + JSON.stringify(room));

Client Code:客户代码:

var localVideo;
var remoteVideo;
var peerConnection;
var uuid;
var constraints = {
        video: true,
        audio: true,
    };

var peerConnectionConfig = {
    'iceServers': [
        {'urls': 'stun:stun.services.mozilla.com'},
        {'urls': 'stun:stun.l.google.com:19302'},
    ]
};

function pageReady() {
    uuid = uuid(); 

    localVideo = document.getElementById('localVideo');
    remoteVideo = document.getElementById('remoteVideo');
    serverConnection = new WebSocket('wss://' + window.location.hostname + ':443');
    serverConnection.onmessage = gotMessageFromServer;

    if(navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices.getUserMedia(constraints).then(getUserMediaSuccess).catch(errorHandler);

    } else {
        alert('Your browser does not support getUserMedia API');
    }
}

//CB if it is possible to run gerUserMedia then gets the local video stream
function getUserMediaSuccess(stream) {
    localStream = stream;
    localVideo.src = window.URL.createObjectURL(stream); //Depreciated
    //localVideo.srcObject = stream;
}


//CB this function starts the call 
function start(isCaller) {
    peerConnection = new RTCPeerConnection(peerConnectionConfig);
    peerConnection.onicecandidate = gotIceCandidate;
    peerConnection.onaddstream = gotRemoteStream;
    //peerConnection.ontrack = gotRemoteStream;
    peerConnection.addStream(localStream);

    if(isCaller) {
        peerConnection.createOffer().then(createdDescription).catch(errorHandler);
    }
}

function gotMessageFromServer(message) {
    if(!peerConnection) start(false);

    var signal = JSON.parse(message.data);

    // Ignore messages from ourself
    if(signal.uuid == uuid) return;

    if(signal.sdp) {
        peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(function() {
            // Only create answers in response to offers
            if(signal.sdp.type == 'offer') {
                peerConnection.createAnswer().then(createdDescription).catch(errorHandler);
            }
        }).catch(errorHandler);
    } else if(signal.ice) {
        peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler);
    }
}

function gotIceCandidate(event) {
    if(event.candidate != null) {
        serverConnection.send(JSON.stringify({'ice': event.candidate, 'uuid': uuid}));
    }
}

function createdDescription(description) {
    console.log('got description');

    peerConnection.setLocalDescription(description).then(function() {
        serverConnection.send(JSON.stringify({'sdp': peerConnection.localDescription, 'uuid': uuid}));
    }).catch(errorHandler);
}

function gotRemoteStream(event) {
    console.log('got remote stream');
    remoteVideo.src = window.URL.createObjectURL(event.stream); 
    //remoteVideo.src = event.stream;
}

function errorHandler(error) {
    console.log(error);
}

// Taken from http://stackoverflow.com/a/105074/515584
// Strictly speaking, it's not a real UUID, but it gets the job done here
function uuid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  }

  return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

You need to change the server's code in the example.您需要更改示例中的服务器代码。 Right now it is just broadcasting all the messages to all other clients.现在它只是向所有其他客户端广播所有消息。 What you need to do is right a logic at server side to send messages to only those clients with same room id.您需要做的是正确的服务器端逻辑,仅向具有相同房间 ID 的客户端发送消息。

I have written a webRTC based p2p scalable broadcast following Shane Tully's example. 我已经按照 Shane Tully 的例子编写了一个基于 webRTC 的 p2p 可扩展广播。 Click here to see 点击这里查看

You can follow from here and get an idea on what i mean by sending signalling messages to specific clients only.您可以从这里开始,通过仅向特定客户端发送信令消息来了解我的意思。 In your case message broadcasting should occur only for those clients having the same room id.在您的情况下,消息广播应该只发生在那些具有相同房间 ID 的客户端上。 I hope this helps !!我希望这会有所帮助!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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