广州营销型网站建设培训站长seo综合查询
背景:
平时我们很少会需要使用到点对点单独的通讯,即p2p,一般都是点对服务端通讯,但p2p也有自己的好处,即通讯不经过服务端,从服务端角度这个省了带宽和压力,从客户端角度,通讯是安全,且快速的,当然有些情况下可能速度并不一定快。那么如何实现p2p呢?
解决办法:
webrtc的RTCPeerConnection就实现了p2p的功能,使用RTCPeerConnection需要理解一些概念,什么是信令,信令交换的过程,信令服务器。
信令
2个设备需要通讯,就需要知道对方的在互联网上的公开地址,一般情况下2个设备都是不会直接拥有一个公网的ip地址,所以他们之间的通讯,就需要如何在公网找到自己的方式,路由信息告诉对方,通常这个信息都是临时的,并非永久,当对方获取到这个信息后,就可以通过网络找到彼此的实际路由路径,从而进行通讯,这个信息就是信令(位置信息)。
信令的交换过程:
假设2个设备,p1要和p2进行通讯
1.p1发起邀请阶段
const offer = await p1.createOffer();//创建邀请信令
await p1.setLocalDescription(offer);//设置为本地信令send(JSON.stringify(offer));//把邀请信令发送给对方,至于怎么发送,一般是需要一个第3方的信令服务器来转发这个信息
2.p2收到邀请阶段
当收到p1发起的有邀请信令offer后
await p2.setRemoteDescription(new RTCSessionDescription(JSON.parse(offer)));//设置为远端的信令const answer = await p2.createAnswer();//创新一个应答信令,告诉p1我的位置
await pc.setLocalDescription(answer);//设置我的位置send(JSON.stringify(answer ));将位置信息发送给p1
3.p1收到应答信息阶段
await p2.setRemoteDescription(new RTCSessionDescription(JSON.parse(answer )));//设置为远端的信令
4.处理onicecandidate事件,确认要不要通讯
await p2.addIceCandidate(new RTCIceCandidate(JSON.parse(candidate)));
完成上述几个阶段,正常来说就能开始通讯了
数据通讯DataChannel的使用
发送端
// 创建PeerConnection对象
const pc = new RTCPeerConnection();// 创建DataChannel
const dataChannel = pc.createDataChannel('myDataChannel');// 监听DataChannel的open事件
dataChannel.onopen = () => {console.log('DataChannel已打开');
};// 监听DataChannel的error事件
dataChannel.onerror = (error) => {console.error('DataChannel错误:', error);
};// 监听DataChannel的close事件
dataChannel.onclose = () => {console.log('DataChannel已关闭');
};// 发送文本消息
function sendMessage(message) {dataChannel.send(message);
}// 发起PeerConnection连接
// ...// 在某个事件触发时调用sendMessage()发送消息
// sendMessage('