聊天室模型不一样考虑的问题也不一样
1.websocket文本聊天
* step1 : 向聊天室所有用户(不包括该用户自己)发送当前用户上线信息。客户端用户栏回添加此用户
* step2 : 将该用户添加至连接池中
* step3 : 向该用户发送该聊天室所有用户列表
* 注:step1 和 step2 顺序颠倒时,会在客户端显示两个"自己"
A客户端向服务器发送消息,服务器向所有连接上的websocket客户端发送消息。
2.webrtc聊天室查看所有人音视频
A客户端已经加入聊天室,B客户端后加入。
B客户端
step1:B客户端加入后获取所有在线用户。
step2:向所有PeerConnection发送Offer类型信令
//向所有PeerConnection发送Offer类型信令
skyrtc.prototype.sendOffers = function() {
var i, m,
pc,
that = this,
pcCreateOfferCbGen = function(pc, socketId) {
return function(session_desc) {
pc.setLocalDescription(session_desc);
that.socket.send(JSON.stringify({
"eventName": "__offer",
"data": {
"sdp": session_desc,
"socketId": socketId
}
}));
};
},
pcCreateOfferErrorCb = function(error) {
console.log(error);
};
for (i = 0, m = this.connections.length; i < m; i++) {
pc = this.peerConnections[this.connections[i]];
pc.createOffer(pcCreateOfferCbGen(pc, this.connections[i]), pcCreateOfferErrorCb);
}
};
step3:接收到answer类型信令后将对方的session描述写入PeerConnection中
//接收到answer类型信令后将对方的session描述写入PeerConnection中
skyrtc.prototype.receiveAnswer = function(socketId, sdp) {
var pc = this.peerConnections[socketId];
pc.setRemoteDescription(new nativeRTCSessionDescription(sdp));
};
A客户端:
step1:接收到Offer类型信令后作为回应返回answer类型信令
//接收到Offer类型信令后作为回应返回answer类型信令
skyrtc.prototype.receiveOffer = function(socketId, sdp) {
var pc = this.peerConnections[socketId];
this.sendAnswer(socketId, sdp);
}; //发送answer类型信令
skyrtc.prototype.sendAnswer = function(socketId, sdp) {
var pc = this.peerConnections[socketId];
var that = this;
pc.setRemoteDescription(new nativeRTCSessionDescription(sdp));
pc.createAnswer(function(session_desc) {
pc.setLocalDescription(session_desc);
that.socket.send(JSON.stringify({
"eventName": "__answer",
"data": {
"socketId": socketId,
"sdp": session_desc
}
}));
}, function(error) {
console.log(error);
});
};
参考:
https://segmentfault.com/a/1190000000436544