最简单的WebRTC示例

http://blog.gopersist.com/page4/index.html

http://www.blogjava.net/linli/archive/2014/10/21/418910.html

在学习WebRTC时,网上的示例大多代码较多,以下是参考那些代码简化的一个WebRTC一对一的示例,在chrome 37下测试通过。其中iceServer可省略,没有iceServer时在同一个局域网下仍可通讯。

客户端代码:

<html>
<body>
    Local: <br>
    <video id="localVideo" autoplay></video><br>
    Remote: <br>
    <video id="remoteVideo" autoplay></video>

    <script>
        // 仅仅用于控制哪一端的浏览器发起offer,#号后面有值的一方发起
        var isCaller = window.location.href.split('#')[1];

        // 与信令服务器的WebSocket连接
        var socket = new WebSocket("ws://127.0.0.1:3000");

        // stun和turn服务器
        var iceServer = {
            "iceServers": [{
                "url": "stun:stun.l.google.com:19302"
            }, {
                "url": "turn:numb.viagenie.ca",
                "username": "webrtc@live.com",
                "credential": "muazkh"
            }]
        };

        // 创建PeerConnection实例 (参数为null则没有iceserver,即使没有stunserver和turnserver,仍可在局域网下通讯)
        var pc = new webkitRTCPeerConnection(iceServer);

        // 发送ICE候选到其他客户端
        pc.onicecandidate = function(event){
            if (event.candidate !== null) {
                socket.send(JSON.stringify({
                    "event": "_ice_candidate",
                    "data": {
                        "candidate": event.candidate
                    }
                }));
            }
        };

        // 如果检测到媒体流连接到本地,将其绑定到一个video标签上输出
        pc.onaddstream = function(event){
            document.getElementById('remoteVideo').src = URL.createObjectURL(event.stream);
        };

        // 发送offer和answer的函数,发送本地session描述
        var sendOfferFn = function(desc){
            pc.setLocalDescription(desc);
            socket.send(JSON.stringify({ 
                "event": "_offer",
                "data": {
                    "sdp": desc
                }
            }));
        },
        sendAnswerFn = function(desc){
            pc.setLocalDescription(desc);
            socket.send(JSON.stringify({ 
                "event": "_answer",
                "data": {
                    "sdp": desc
                }
            }));
        };

        // 获取本地音频和视频流        navigator.webkitGetUserMedia({            "audio": true,            "video": true        }, function(stream){            //绑定本地媒体流到video标签用于输出            document.getElementById('localVideo').src = URL.createObjectURL(stream);            //向PeerConnection中加入需要发送的流            pc.addStream(stream);            //如果是发起方则发送一个offer信令            if(isCaller){                pc.createOffer(sendOfferFn, function (error) {                    console.log('Failure callback: ' + error);                });            }        }, function(error){            //处理媒体流创建失败错误            console.log('getUserMedia error: ' + error);        });        //处理到来的信令        socket.onmessage = function(event){            var json = JSON.parse(event.data);            console.log('onmessage: ', json);            //如果是一个ICE的候选,则将其加入到PeerConnection中,否则设定对方的session描述为传递过来的描述            if( json.event === "_ice_candidate" ){                pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));            } else {                pc.setRemoteDescription(new RTCSessionDescription(json.data.sdp));                // 如果是一个offer,那么需要回复一个answer                if(json.event === "_offer") {                    pc.createAnswer(sendAnswerFn, function (error) {                        console.log('Failure callback: ' + error);                    });                }            }        };    </script></body></html>


实现WebRTC时,信令服务器是必须的,它帮助客户端之间进行沟通。
这里使用Node.js的ws模块来实现一个WebSocket服务作为信令服务器。另外使用express模块让它提供html页面的访问。
server.js代码如下:

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

server.listen(3000);

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

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({server: server});

// 存储socket的数组,这里只能有2个socket,每次测试需要重启,否则会出错
var wsc = [],
index = 1;

// 有socket连入
wss.on('connection', function(ws) {
    console.log('connection');

    // 将socket存入数组
    wsc.push(ws);

    // 记下对方socket在数组中的下标,因为这个测试程序只允许2个socket
    // 所以第一个连入的socket存入0,第二个连入的就是存入1
    // otherIndex就反着来,第一个socket的otherIndex下标为1,第二个socket的otherIndex下标为0
    var otherIndex = index--,
    desc = null;

    if (otherIndex == 1) {
        desc = 'first socket';
    } else {
        desc = 'second socket';
    }

    // 转发收到的消息
    ws.on('message', function(message) {
        var json = JSON.parse(message);
        console.log('received (' + desc + '): ', json);

        wsc[otherIndex].send(message, function (error) {
            if (error) {
                console.log('Send message error (' + desc + '): ', error);
            }
        });
    });
});


使用npm安装需要的模块后使用node server.js启动服务。
测试时使用Chrome浏览器:
第一个浏览器窗口访问页面:http://127.0.0.1:3000,在弹出的提示中允许使用摄像头和麦克风。
第二个浏览器窗口访问页面:http://127.0.0.1:3000#true,#true表示它是一个发起方,在弹出的提示中同样允许使用摄像头和麦克风。
这时页面中应当可以看到2个画面,一个是本地的,一个是远端的。

将代码中的IP稍做调整后部署到外网,即可在2个不同的地点访问这个页面进行实时通讯。


微信订阅号:
源文地址:http://blog.gopersist.com/2014/10/21/webrtc-simple/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: WebRTC是一种用于实现浏览器之间实时通信的开源项目。下面是一个简单WebRTC C语言示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <webrtc/api/peerconnectioninterface.h> void CreateOfferCallback(webrtc::SessionDescriptionInterface* desc) { std::string sdp; desc->ToString(&sdp); printf("SDP offer:\n%s\n", sdp.c_str()); } int main() { // 初始化PeerConnection库 webrtc::PeerConnectionFactoryInterface* peer_connection_factory = webrtc::CreatePeerConnectionFactory(); // 创建一个PeerConnection webrtc::PeerConnectionInterface::RTCConfiguration config; webrtc::PeerConnectionInterface* peer_connection = peer_connection_factory->CreatePeerConnection(config, nullptr); if (!peer_connection) { printf("Failed to create PeerConnection\n"); return -1; } // 配置PeerConnection的本地媒体 webrtc::MediaConstraintsInterface* constraints = new webrtc::MediaConstraintsInterface(); peer_connection->AddStream(constraints); // 创建offer并设置offer回调 peer_connection->CreateOffer(new webrtc::CreateOfferCallback, constraints); // 主循环 while (1) { // 处理PeerConnection的事件 peer_connection->ProcessMessages(); } // 释放资源 delete constraints; delete peer_connection; delete peer_connection_factory; return 0; } ``` 这段示例代码展示了如何使用WebRTC的C接口创建一个简单的PeerConnection,并创建Offer和接收Answer来建立连接。在代码中,我们首先初始化PeerConnectionFactory,然后创建一个PeerConnection,并设置本地媒体。接下来创建Offer并设置Offer回调,通过回调函数可以获得生成的SDP(会话描述协议)Offer。最后在主循环中处理PeerConnection的事件,直到程序结束。注意,这段代码仅仅是一个示例,实际应用中可能需要处理更多的细节和错误处理。 ### 回答2: WebRTC是一种用于实时音视频通信的开源技术,其C语言示例代码可以用于实现基于C语言的音视频通信应用。下面是一个简单WebRTC C示例代码: ```c // 包含WebRTC相关的头文件 #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> // WebRTC的初始化函数 int webrtc_init() { // 初始化WebRTC库 // ... return 0; } // 创建PeerConnection(对等连接) int create_peer_connection() { // 创建PeerConnection对象 // ... return 0; } // 发送音视频数据 int send_media_data(uint8_t* data, size_t size) { // 将音视频数据通过WebRTC发送出去 // ... return 0; } // 接收音视频数据 int receive_media_data(uint8_t* data, size_t size) { // 从WebRTC接收音视频数据 // ... return 0; } // 主函数 int main() { // 初始化WebRTC if (webrtc_init() != 0) { printf("WebRTC初始化失败\n"); return 1; } // 创建PeerConnection if (create_peer_connection() != 0) { printf("创建PeerConnection失败\n"); return 1; } // 发送和接收音视频数据 uint8_t data[] = {1, 2, 3, 4, 5}; if (send_media_data(data, sizeof(data)) != 0) { printf("发送音视频数据失败\n"); return 1; } uint8_t received_data[10]; if (receive_media_data(received_data, sizeof(received_data)) != 0) { printf("接收音视频数据失败\n"); return 1; } // 打印接收到的音视频数据 printf("接收到的音视频数据: "); for (size_t i = 0; i < sizeof(received_data); ++i) { printf("%d ", received_data[i]); } printf("\n"); return 0; } ``` 请注意,以上示例代码只是简单演示了WebRTC在C语言中的使用,实际应用中还需要根据具体需求进行更多的配置和处理。也需要使用WebRTC的库和函数来进行实际的音视频传输、信令等操作。 ### 回答3: WebRTC(Web实时通信)是一个开放源代码的项目,用于实时音视频通信和数据传输。它提供了一组API和一些示例代码,使开发者可以在网页中实现音视频通信功能。 下面是一个简单WebRTC C语言示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <webrtc.h> // 声明回调函数 void onReceiveData(const char* data, int length) { printf("Received data: %s\n", data); } int main() { // 初始化WebRTC webrtc_init(); // 创建PeerConnection PeerConnection* pc = createPeerConnection(); // 设置回调函数 pc->data_received = onReceiveData; // 发送数据 const char* data = "Hello, WebRTC!"; int length = strlen(data); pc->send_data(data, length); // 等待数据接收 webrtc_loop(); // 销毁PeerConnection destroyPeerConnection(pc); // 释放WebRTC资源 webrtc_cleanup(); return 0; } ``` 这段代码使用了WebRTC的C语言库,实现了一个简单的数据传输示例。首先,通过调用`webrtc_init()`函数来初始化WebRTC库。然后,使用`createPeerConnection()`函数创建一个PeerConnection对象,表示与远程端的连接。通过设置回调函数`onReceiveData()`,当接收到数据时会调用该函数。接下来,使用`send_data()`函数发送一段数据。最后,调用`webrtc_loop()`函数开始接收数据,并一直等待,直到关闭程序。在程序结束前,要通过`destroyPeerConnection()`函数销毁PeerConnection对象,最后通过`webrtc_cleanup()`函数释放WebRTC库的资源。 这只是一个简单示例代码,实际使用WebRTC还需要更多的代码来处理网络连接、音视频编解码等功能。这段代码可以作为一个入门示例,帮助开发者理解WebRTC的基本使用方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值