首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >WebRTC:为简单的WebRTC & WebSocket应用程序添加空间-需要建议

WebRTC:为简单的WebRTC & WebSocket应用程序添加空间-需要建议
EN

Stack Overflow用户
提问于 2017-08-12 16:17:35
回答 1查看 2.2K关注 0票数 0

我对webrtc和编码非常陌生,如果这不是一个明确的问题,我很抱歉。

我遵循了Shane示例这里,并将其修改为在我的AWS服务器上运行。它的运行查找,但它只允许我一次一个连接。我希望让用户输入我的URL,然后是一个房间名称,以便连接到一个房间。

例如: www.myurl.com/apple,苹果将在其中创建一个房间。下面是一个例子--如果在这个URL的末尾添加/apppl,它将创建一个房间。(本例的代码相当复杂,使用socket.io。其中我使用ws for Node来创建websockets)

有人对此有什么建议吗?我的总体目标是创建一个结合了视频调用功能的Android,并使用WebView显示调用功能,这就是为什么我需要对每一对设备使用不同的URL,以便它们都能访问同一个房间。

提前谢谢你!克莱尔

服务器代码:

代码语言:javascript
运行
复制
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));

客户端代码:

代码语言:javascript
运行
复制
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();
}
EN

回答 1

Stack Overflow用户

发布于 2020-06-11 03:22:15

您需要在示例中更改服务器的代码。现在,它只是向所有其他客户广播所有的信息。您需要做的是在服务器端正确地将消息发送给那些拥有相同房间id的客户端。

我按照Shane的例子编写了一个基于webRTC的p2p可伸缩广播。点击这里查看

您可以从这里开始,只向特定客户端发送信令消息,从而了解我的意思。在您的情况下,消息广播应该只发生在那些具有相同房间标识的客户端。希望这能帮上忙!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45652426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档