webrtc学习笔记六(datachannel+websocket)

只有datachannel的例子,websocket作为转发用,
建立连接后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);
            }
        });
    });
});


webrtc_datachannle.html

<html>
<body>
<button id="sendButton" onclick="sendData()">Send</button>
<textarea id="dataChannelSend" >abc</textarea>
<textarea id="dataChannelReceive" ></textarea>

<script>
        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" ){
                pc.addIceCandidate(new RTCIceCandidate(json.data.candidate));
            } else {
                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;
		};
        function sendData() {
		  var data = document.getElementById('dataChannelSend').value;
		  console.log("---->>>>sendData():"+data);
		  sendChannel.send(data);
		}
		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);
            });
        }
        
    </script>
</body>
</html>

你可能感兴趣的:(WebRTC)