对比上一篇webrtc入门实战,进阶篇中新增的点最重要的就是信令服务器,入门中我们是在同一个html页面中进行信息交换,现实中我们视频通话当然是身在远处了,那么就需要一个信令服务器来交互通信“地址”(sdp等信息)。
此处来实现一个基于nodejs的简单信令服务(未发布,局域网可用),使得下一篇的完整例子可以实现真实的视频通话。
安装依赖:
// npm node 都是需要的哈
npm install ws;
服务器代码:
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const wss = new WebSocketServer({
port: 3002
}, () => {
console.log('open')
})
let clents = [];
wss.on('connection', (ws) => {
console.log('some connection');
// ws.send(ws)
ws.on('message', (message) => {
let res = {};
try {
res = JSON.parse(message.toString());
} catch { console.log(message + '不是json') }
const { type, name } = res;
console.log(type);
if (type === 'init') {
clents = clents.filter(i => i.name !== name); // 防止重复
clents.push({ name, target: ws });
} else {
// if (type === 'offer' || type === 'answer' || type==='ice')
clents.filter(i => i.name !== name).forEach(({ target }) => {
// 广播 , 注意就不用给自己发了
target.send(JSON.stringify(res))
})
}
})
})
wss.on('close', () => {
console.log('wss closed')
})
启动命令:
node server.js // 你保存叫啥就运行啥
................稍微修改一下,可以按自己的接下去想做的发挥..........
给指定在线用户拨打视频
webrtc进阶实战之完整版 - 简书 (jianshu.com)
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const wss = new WebSocketServer({
port: 3002
}, () => {
console.log('open')
})
let clents = [];
wss.on('connection', (ws) => {
console.log('some connection');
// ws.send(ws)
ws.on('message', (message) => {
let res = {};
try {
res = JSON.parse(message.toString());
} catch { console.log(message + '不是json') }
const { type, name, targetName } = res;
console.log(type);
if (type === 'init') {
clents = clents.filter(i => i.name !== name); // 防止重复
clents.push({ name, target: ws });
console.log(clents.map(i => i.name))
clents.forEach(({ target }) => {
target.send(JSON.stringify({ type: 'list', list: clents.map(i => i.name) })) // 广播一份在线列表
})
} else {
// if (type === 'offer' || type === 'answer' || type==='ice')
const target = (clents.filter(i => i.name === targetName)[0] || {}).target;
target && target.send(JSON.stringify(res)); // 发送给指定人员
}
})
})
wss.on('close', () => {
console.log('wss closed')
})