欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

webrtc学习笔记五(视频流和datachannel一起使用的例子)

程序员文章站 2022-07-08 16:45:09
...
2020年5月9日更新,5年前的例子运行不了了,更新下html
主要是chrome的URL的api变了
在mac的chrome上
把 document.getElementById('remoteVideo').src = window.URL.createObjectURL(event.stream);
改成
document.getElementById('remoteVideo').srcObject = event.stream;
参考:https://*.com/questions/27120757/failed-to-execute-createobjecturl-on-url


视频和datachannel一起使用的两个页面的例子
网上的datachannel只能在一个页面,
根据视频的改了下两个页面可以传数据了
疑问:ondatachannel似乎没用上
先打开192.168.137.27:8081/js/webrtc2.html
另一台电脑打开
192.168.137.27:8081/js/webrtc2.html#true
视频正确两个都显示了才正确,
websocket三个页面有问题,没优化

server.js
//http://www.blogjava.net/linli/archive/2014/10/21/418910.html
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});
function writeObj(obj){ 
    var description = ""; 
    for(var i in obj){   
        var property=obj[i];   
        description+=i+" = "+property+"\n";  
    }   
    console.log(description); 
} 
// 存储socket的数组,这里只能有2个socket,每次测试需要重启,否则会出错
var wsc = [],
index = 1;
// 有socket连入
wss.on('connection', function(ws) {
    console.log('connection:');
    //writeObj(ws);
    // 将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);
        console.log('otherIndex ---('+desc+')(' + otherIndex + '): '+json.event);
        wsc[otherIndex].send(message, function (error) {
            if (error) {
                console.log('Send message error (' + desc + '): ', error);
            }
        });
    });
});

webrtc2.html
<html>
<body>
<button id="sendButton" onclick="sendData()">Send</button>
<textarea id="dataChannelSend" >abc</textarea>
<textarea id="dataChannelReceive" ></textarea>
    Local: <br>
    
    <video id="localVideo" autoplay></video><br>
    Remote: <br>
    <video id="remoteVideo" autoplay></video>

<script>
		function writeObj(obj){ 
		    var description = ""; 
		    for(var i in obj){   
		        var property=obj[i];   
		        description+=i+" = "+property+"\n";  
		    }   
		    console.log(description); 
		}
        var isCaller = window.location.href.split('#')[1];
        var socket = new WebSocket("ws://192.168.137.27:3000");
        socket.onmessage = function(event){
            var json = JSON.parse(event.data);
            //console.log('onmessage: ', json);
            //如果是一个ICE的候选,则将其加入到PeerConnection中,否则设定对方的session描述为传递过来的描述
            if( json.event === "_ice_candidate" ){
            //	console.log("_ice_candidate:---->");
            //	writeObj(json.data.candidate);
                pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));
            } else {
            //	console.log("not _ice_candidate:---->");
            //	writeObj(json.data.sdp);
                pc.setRemoteDescription(new RTCSessionDescription(json.data.sdp));
                console.log("---------------->pc.setRemote");
                // 如果是一个offer,那么需要回复一个answer
                if(json.event === "_offer") {
                	console.log("------->createAnswer");
                    pc.createAnswer(function(desc){
			            pc.setLocalDescription(desc);
			            console.log("---------------->pc.setLocal");
			            socket.send(JSON.stringify({ 
			                "event": "_answer",
			                "data": {
			                    "sdp": desc
			                }
			            }));
			        }, function (error) {
                        console.log('Failure callback: ' + error);
                    });
                }else{
                	console.log("------->receive Answer---('"+json.event+"')");
                }
                
            }
        };
        var iceServer = null;
        var pc = new webkitRTCPeerConnection(iceServer,{optional: [{RtpDataChannels: true}]});
        try {
		    sendChannel = pc.createDataChannel('sendDataChannel',{reliable: true});
		} catch (e) {
		    alert('createDataChannel() failed with exception: ' + e.message);
		}
		sendChannel.onopen = console.log('--Send channel open state is : ' +sendChannel.readyState);
  		sendChannel.onclose = console.log('--Send channel close  state is: ' +sendChannel.readyState);
        // 发送ICE候选到其他客户端
        pc.onicecandidate = function(event){
        	console.log("onicecandidate----------->");
            if (event.candidate !== null) {
            	console.log("event.candidate   !=   null");
                socket.send(JSON.stringify({
                    "event": "_ice_candidate",
                    "data": {
                        "candidate": event.candidate
                    }
                }));
            }else{
            	console.log("event.candidate   == null");
            }
        };
    	sendChannel.onmessage = function(event) {
    		  console.log("-sendChannel--★★★★★---ondatachannel");
			  document.getElementById('dataChannelReceive').value = event.data;
		};
        /*pc.ondatachannel = function(event) {
			console.log("-receiveChannel--★★★★★---ondatachannel");
			receiveChannel = event.channel;
			receiveChannel.onmessage = function(event) {
				  document.getElementById('dataChannelReceive').value = event.data;
			};
			receiveChannel.onopen = console.log('--Receive channel open state is: ' + receiveChannel.readyState);;
			receiveChannel.onclose = console.log('--Receive channel close state is: ' + receiveChannel.readyState);;
		};*/
        // 如果检测到媒体流连接到本地,将其绑定到一个video标签上输出
        pc.onaddstream = function(event){
            //document.getElementById('remoteVideo').src = URL.createObjectURL(event.stream);
           document.getElementById('remoteVideo').srcObject = event.stream;
        };
        function sendData() {
        	
		  var data = document.getElementById('dataChannelSend').value;
		  console.log("---->>>>sendData():"+data);
		  sendChannel.send(data);
		}
        navigator.webkitGetUserMedia({
            "audio": true,
            "video": true
        }, function(stream){
           // document.getElementById('localVideo').src = URL.createObjectURL(stream);
            document.getElementById('localVideo').srcObject = stream;
            pc.addStream(stream);
            if(isCaller){
            	console.log("------->createOffer");
                pc.createOffer(function(desc){
                //	console.log(desc);
		            pc.setLocalDescription(desc);
		            console.log("---------------->pc.setLocal");
		            socket.send(JSON.stringify({ 
		                "event": "_offer",
		                "data": {
		                    "sdp": desc
		                }
		            }));
		        }, function (error) {
                    console.log('Failure callback: ' + error);
                });
            }
        }, function(error){
            console.log('getUserMedia error: ' + error);
        });
        
    </script>
</body>
</html>
相关标签: webrtc