【p2p】RTCMultiConnection

API

//创建
new RTCMultiConnection()

//参数
//读写参数
socketURL = 'https://rtcmulticonnection.herokuapp.com:443/'//服务器地址
session = {
    data: true// 文本或文件
    audio: true,//语言
    video: true//视频
}
*enableFileSharing = true//使能够分享文件
*maxParticipantsAllowed = 10//设置最大用户数量
//只读参数
userid
sessionid

//方法
onopen = e=>{}//打开
*closeSocket()//关闭
send('')//发送
onmessage = e=> {//接收
	e.userid//发送方
	e.data//数字或字符串
}
shareFile()//分享文件
openOrJoin('roomid')

*changeUserId('new-userid')//修改用户ID (不会更新自己id的远程记录;无法与新加入的用户通信)
checkPresence('roomid')//切换房间 (切换房间后自己收不到上一个房间的,但自己的消息会被发到上一个房间)

peers() //自己外用户的情况
*shareFile(lastSelectedFile, event.userid)

*setUserPreferences = p=>{
    p.dontAttachLocalStream = true;//不附加流
    p.dontGetRemoteStream = true;//不获取远程流
    return p;
}

常用功能的实现

//导入依赖包
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>

//切换房间
function check(roomId) {
        connection.checkPresence(roomId, function(isRoomEists, roomid) {
            connection.close();
            connection.openOrJoin(roomid)
        });
    }

//向特定用户发送数据

//方法1
connection.peers.send(message,userid)
//方法2
var data={"type":"text","message":"test5","last":true,"isobject":false}
data = JSON.stringify(data)
connection.peers[userid].channels[0].send(data)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>P2P test</title>
    <script>
        console.oldLog = console.log;
        console.log = function(str) {
            console.oldLog(str);
            var tag=document.createElement("div")
            tag.innerHTML=str
            document.body.append(tag)
        }
    </script>
</head>
<body>
    <script src="http://youku3d.com/smart3d/lib/RTCMultiConnection.js"></script>
    <script src="http://youku3d.com/smart3d/lib/socket.io.js"></script>
    <script src="http://youku3d.com/smart3d/lib/FileBufferReader.js"></script>
    <script>
        var connection = new RTCMultiConnection()
        connection.socketURL = "http://110.40.255.87:9001/"
        connection.socketMessageEvent = 'file-sharing-demo';
        connection.sdpConstraints.mandatory = {
            OfferToReceiveAudio: false,
            OfferToReceiveVideo: false
        };
        connection.enableFileSharing = true;
        connection.session = {
            data: true
        }
        connection.onmessage = function(event) {
            console.log(event.userid+" : "+event.data)
        };
        window.time0=performance.now()
        connection.onopen = function(e) {
            console.log({
                number:1+connection.peers.getLength(),
                time:performance.now()-window.time0
            })
            window.time=0
            setInterval(()=>{
                console.log('send:'+time)
                connection.send(time)
                window.time++
            },2500)
        }
        connection.openOrJoin("myRoom1");
    </script>
</body>
</html>

server.js

var httpServer = require('http');
const RTCMultiConnectionServer = require('rtcmulticonnection-server');
const jsonPath = {
    config: 'config.json',
    logs: 'logs.json'
}
const BASH_COLORS_HELPER = RTCMultiConnectionServer.BASH_COLORS_HELPER;
const getValuesFromConfigJson = RTCMultiConnectionServer.getValuesFromConfigJson;
const getBashParameters = RTCMultiConnectionServer.getBashParameters;
var config = getValuesFromConfigJson(jsonPath);
config = getBashParameters(config, BASH_COLORS_HELPER);
var PORT = config.port;

var httpApp = httpServer.createServer((req,res)=>console.log(req,res));
RTCMultiConnectionServer.beforeHttpListen(httpApp, config);
httpApp = httpApp.listen(process.env.PORT || PORT, process.env.IP || "0.0.0.0", function() {
    RTCMultiConnectionServer.afterHttpListen(httpApp, config);
});
// --------------------------
// socket.io codes goes below
const ioServer = require('socket.io');
ioServer(httpApp, {
    cors: {
        origin: ['http://localhost:8080','http://localhost:63342','http://localhost:8081'],
        credentials: true
    }
}).on('connection', function(socket) {
    RTCMultiConnectionServer.addSocket(socket, config);
});

跨域请求
CORS 是跨域资源分享(Cross-Origin Resource Sharing)的缩写。它是 W3C 标准,属于跨源 AJAX 请求的根本解决方法。

ioServer(httpApp, {
    cors: {
        origin: ['http://localhost:8080','http://localhost:63342','http://localhost:8081'],
        credentials: true
    }
}).on('connection', function(socket) {
    RTCMultiConnectionServer.addSocket(socket, config);
});

同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

RTCMultiConnection与RTCPeerConnection的关系

//RTCPeerConnection
connection.peers[userid].peer
//RTCDataChannel
connection.peers[userid].peer.channel

<PeerInitiator>.addRemoteSdp		-- setRemoteDescription
<PeerInitiator>.createOfferOrAnswer	-- setLocalDescription

一次提议和应答操作建立了一个单向通信的信道

onicecandidate

pc.onicecandidate = function(event) {
  if (event.candidate) {
    // Send the candidate to the remote peer
  } else {
    // All ICE candidates have been sent
    //当协议结束时candidate为 null.
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值