jjzjj

javascript - 实现信令的工作 Hello World WebRTC DataChannel 示例

coder 2024-05-16 原文

目的是让它成为一个 Community Wiki帖子保持最新,因此有兴趣使用 WebRTC DataChannels 实现 JSON 消息浏览器到浏览器 (p2p) 通信的开发人员有简单而实用的示例。

WebRTC DataChannels 是实验性的,仍处于草案阶段。目前看来,网络是过时的 WebRTC 示例的雷区,如果开发人员正在尝试学习 RTCDataChannel API,则更是如此。

如今可在 WebRTC 中使用的简单而实用的单页示例 compliant browsers似乎很难找到。例如,some examples省略信令实现,others仅适用于单个浏览器(例如 Chrome-Chrome),many由于最近的 API 更改而过时,并且 others非常复杂,它们对入门造成了障碍。

请发布满足以下条件的示例(如果不满足,请说明):

  1. 客户端代码为 1 页(200 行或更少)
  2. 服务端代码一页,技术引用(如node.js、php、python等)
  3. 实现了信令机制并引用了协议(protocol)技术(例如 WebSockets、long pollingGCM 等)
  4. 运行跨浏览器(Chrome、Firefox、Opera 和/或 Bowser)的工​​作代码
  5. 最少的选项,错误处理,abstraction等——意图是一个基本的例子

最佳答案

这是一个使用 HTML5 WebSockets 发送信号和 node.js 后端的工作示例

信号技术:WebSockets
客户端:纯 html/javascript
服务器:node.js , ws
最后测试:Firefox 40.0.2Chrome 44.0.2403.157 mOpera 31.0.1889.174


客户端代码:

<html>
<head>
</head>
<body>
    <p id='msg'>Click the following in different browser windows</p>
    <button type='button' onclick='init(false)'>I AM Answerer Peer (click first)</button>
    <button type='button' onclick='init(true)'>I AM Offerer Peer</button>

<script>
    (function() {   
        var offererId = 'Gandalf',   // note: client id conflicts can happen
            answererId = 'Saruman',  //       no websocket cleanup code exists
            ourId, peerId,
            RTC_IS_MOZILLA = !!window.mozRTCPeerConnection,
            RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.msRTCPeerConnection,
            RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.msRTCSessionDescription,
            RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate || window.msRTCIceCandidate,
            rtcpeerconn = new RTCPeerConnection(
                    {iceServers: [{ 'url': 'stun:stun.services.mozilla.com'}, {'url': 'stun:stun.l.google.com:19302'}]}, 
                    {optional: [{RtpDataChannels: false}]}
                ),
            rtcdatachannel, 
            websocket = new WebSocket('ws://' + window.location.hostname + ':8000'),
            comready, onerror;

        window.init = function(weAreOfferer) {
            ourId = weAreOfferer ? offererId : answererId;
            peerId = weAreOfferer ? answererId : offererId;

            websocket.send(JSON.stringify({
                inst: 'init', 
                id: ourId
            }));

            if(weAreOfferer) {

                rtcdatachannel = rtcpeerconn.createDataChannel(offererId+answererId);
                rtcdatachannel.onopen = comready;
                rtcdatachannel.onerror = onerror;

                rtcpeerconn.createOffer(function(offer) {
                    rtcpeerconn.setLocalDescription(offer, function() {
                        var output = offer.toJSON();
                        if(typeof output === 'string') output = JSON.parse(output); // normalize: RTCSessionDescription.toJSON returns a json str in FF, but json obj in Chrome

                        websocket.send(JSON.stringify({
                            inst: 'send', 
                            peerId: peerId, 
                            message: output
                        }));
                    }, onerror);
                }, onerror);
            }
        };

        rtcpeerconn.ondatachannel = function(event) {
            rtcdatachannel = event.channel;
            rtcdatachannel.onopen = comready;
            rtcdatachannel.onerror = onerror;
        };

        websocket.onmessage = function(input) {
            var message = JSON.parse(input.data);

            if(message.type && message.type === 'offer') {
                var offer = new RTCSessionDescription(message);

                rtcpeerconn.setRemoteDescription(offer, function() {
                    rtcpeerconn.createAnswer(function(answer) {
                        rtcpeerconn.setLocalDescription(answer, function() {
                            var output = answer.toJSON();
                            if(typeof output === 'string') output = JSON.parse(output); // normalize: RTCSessionDescription.toJSON returns a json str in FF, but json obj in Chrome

                            websocket.send(JSON.stringify({
                                inst: 'send',
                                peerId: peerId,
                                message: output
                            }));
                        }, onerror);
                    }, onerror);                
                }, onerror);
            } else if(message.type && message.type === 'answer') {              
                var answer = new RTCSessionDescription(message);
                rtcpeerconn.setRemoteDescription(answer, function() {/* handler required but we have nothing to do */}, onerror);
            } else if(rtcpeerconn.remoteDescription) {
                // ignore ice candidates until remote description is set
                rtcpeerconn.addIceCandidate(new RTCIceCandidate(message.candidate));
            }
        };

        rtcpeerconn.onicecandidate = function (event) {
            if (!event || !event.candidate) return;
            websocket.send(JSON.stringify({
                inst: 'send',
                peerId: peerId,
                message: {candidate: event.candidate}
            }));
        };

        /** called when RTC signaling is complete and RTCDataChannel is ready */
        comready = function() {
            rtcdatachannel.send('hello world!');
            rtcdatachannel.onmessage = function(event) {
                document.getElementById('msg').innerHTML = 'RTCDataChannel peer ' + peerId + ' says: ' + event.data;    
            }
        };

        /** global error function */
        onerror = websocket.onerror = function(e) {
            console.log('====== WEBRTC ERROR ======', arguments);
            document.getElementById('msg').innerHTML = '====== WEBRTC ERROR ======<br>' + e;
            throw new Error(e);
        };
    })();
</script>
</body>
</html>

服务器端代码:

var server = require('http').createServer(), 
    express = require('express'),    
    app = express(),
    WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({ server: server, port: 8000 });

app.use(express.static(__dirname + '/static')); // client code goes in static directory

var clientMap = {};

wss.on('connection', function (ws) {
    ws.on('message', function (inputStr) {
        var input = JSON.parse(inputStr);
        if(input.inst == 'init') {
            clientMap[input.id] = ws;
        } else if(input.inst == 'send') {
            clientMap[input.peerId].send(JSON.stringify(input.message));
        }
    });
});

server.on('request', app);
server.listen(80, YOUR_HOSTNAME_OR_IP_HERE, function () { console.log('Listening on ' + server.address().port) });

关于javascript - 实现信令的工作 Hello World WebRTC DataChannel 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172627/

有关javascript - 实现信令的工作 Hello World WebRTC DataChannel 示例的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  4. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  5. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  6. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  7. ruby - JetBrains RubyMine 3.2.4 调试器不工作 - 2

    使用Ruby1.9.2运行IDE提示说需要gemruby​​-debug-base19x并提供安装它。但是,在尝试安装它时会显示消息Failedtoinstallgems.Followinggemswerenotinstalled:C:/ProgramFiles(x86)/JetBrains/RubyMine3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem:Errorinstallingruby-debug-base19x-0.11.30.pre2.gem:The'linecache19'nativegemrequiresinstall

  8. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  9. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  10. ruby - `rescue $!` 是如何工作的? - 2

    我知道全局变量$!包含最新的异常对象,但我对下面的语法感到困惑。谁能帮助我理解以下语法?rescue$! 最佳答案 此构造可防止异常停止您的程序并使堆栈跟踪冒泡。它还会将该异常作为值返回,这很有用。a=get_me_datarescue$!在此行之后,a将保存请求的数据或异常。然后您可以分析该异常并采取相应措施。defget_me_dataraise'Nodataforyou'enda=get_me_datarescue$!puts"Executioncarrieson"pa#>>Executioncarrieson#>>#更现实的

随机推荐