對(duì)比上一篇webrtc入門實(shí)戰(zhàn)综慎,進(jìn)階篇中新增的點(diǎn)最重要的就是信令服務(wù)器诞丽,入門中我們是在同一個(gè)html頁面中進(jìn)行信息交換踊跟,現(xiàn)實(shí)中我們視頻通話當(dāng)然是身在遠(yuǎn)處了姨拥,那么就需要一個(gè)信令服務(wù)器來交互通信“地址”(sdp等信息)绣檬。
此處來實(shí)現(xiàn)一個(gè)基于nodejs的簡(jiǎn)單信令服務(wù)(未發(fā)布璧眠,局域網(wǎng)可用)缩焦,使得下一篇的完整例子可以實(shí)現(xiàn)真實(shí)的視頻通話读虏。
安裝依賴:
// npm node 都是需要的哈
npm install ws;
服務(wù)器代碼:
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); // 防止重復(fù)
clents.push({ name, target: ws });
} else {
// if (type === 'offer' || type === 'answer' || type==='ice')
clents.filter(i => i.name !== name).forEach(({ target }) => {
// 廣播 , 注意就不用給自己發(fā)了
target.send(JSON.stringify(res))
})
}
})
})
wss.on('close', () => {
console.log('wss closed')
})
啟動(dòng)命令:
node server.js // 你保存叫啥就運(yùn)行啥
運(yùn)行
................稍微修改一下袁滥,可以按自己的接下去想做的發(fā)揮..........
給指定在線用戶撥打視頻
webrtc進(jìn)階實(shí)戰(zhàn)之完整版 - 簡(jiǎn)書 (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); // 防止重復(fù)
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)); // 發(fā)送給指定人員
}
})
})
wss.on('close', () => {
console.log('wss closed')
})