This commit is contained in:
2023-09-27 14:26:12 +08:00
parent a7dd2875fa
commit 62a2dc6f1d
4 changed files with 277 additions and 0 deletions

View File

@ -1,2 +1,13 @@
# webrtc # webrtc
webrtc 实现的 p2p 信道 webrtc 实现的 p2p 信道
// 能获取所有在线设备列表
// 随机连接至四个设备, 且按效率扩展收缩
// 将数据拆解同时向多台设备分发, 对端接收后再次分发
// 需要确保全部设备获得全部数据, 每台设备至少一半不重复
// 五色
// 单向链
// 固定填位(矩阵)
// [a1, b1, c1, d1, e1]
// [a2, b2, c2, d2, e2]
// [a3, b3, c3, d3, e3]

50
index.js Normal file
View File

@ -0,0 +1,50 @@
import express from 'express'
import expressWs from 'express-ws'
const app = express()
const wsInstance = expressWs(app)
app.use(express.static('public'))
// Websocket 处理 webRTC 信令
app.ws('/webrtc/:channel', (ws, req) => {
ws.id = req.headers['sec-websocket-key']
ws.channel = req.params.channel
// 设备离开频道时广播给所有在线设备
ws.on('close', () => {
console.log(ws.id, '设备离开频道:', ws.channel, wsInstance.getWss().clients.size)
wsInstance.getWss().clients.forEach(client => {
if (client !== ws && client.readyState === 1 && client.channel === ws.channel) {
client.send(JSON.stringify({ type: 'pull', id: ws.id, channel: ws.channel }))
}
})
})
// 设备发生错误时广播给所有在线设备
ws.on('error', () => {
console.log(ws.id, '设备发生错误:', ws.channel, wsInstance.getWss().clients.size)
wsInstance.getWss().clients.forEach(client => {
if (client !== ws && client.readyState === 1 && client.channel === ws.channel) {
client.send(JSON.stringify({ type: 'error', id: ws.id, channel: ws.channel }))
}
})
})
// 设备发送信令时转发给指定在线设备
ws.on('message', message => {
console.log(ws.id, '设备发送信令:', ws.channel, wsInstance.getWss().clients.size)
const { id } = JSON.parse(message)
wsInstance.getWss().clients.forEach(client => {
if (client !== ws && client.readyState === 1 && client.channel === ws.channel && client.id === id) {
client.send(message)
}
})
})
// 设备加入频道时广播给所有在线设备(也获取所有在线设备)
console.log(ws.id, '设备加入频道:', ws.channel, wsInstance.getWss().clients.size)
wsInstance.getWss().clients.forEach(client => {
if (client !== ws && client.readyState === 1 && client.channel === ws.channel) {
client.send(JSON.stringify({ type: 'push', id: ws.id, channel: ws.channel }))
ws.send(JSON.stringify({ type: 'push', id: client.id, channel: client.channel }))
}
})
})
app.listen(3000, () => console.log('Server started on port 3000'))

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "webrtc",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js",
"start": "node index.js"
},
"author": "",
"license": "GPL-3.0-or-later",
"devDependencies": {
"nodemon": "^3.0.1"
},
"dependencies": {
"express": "^4.18.2",
"express-ws": "^5.0.2"
}
}

196
public/index.html Normal file
View File

@ -0,0 +1,196 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webRTC</title>
</head>
<body>
<div>
<h1>webRTC</h1>
<p>message</p>
</div>
<script type="module">
// webRTC 传递音乐(分别传输文件和操作事件能更流畅)
const music = async function () {
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const host = window.location.host
const ws = new WebSocket(`${protocol}://${host}/webrtc/music`)
const pc = new RTCPeerConnection()
const clients = []
// 监听 ICE 候选事件
pc.onicecandidate = event => {
if (event.candidate) {
const id = clients[0].id
ws.send(JSON.stringify({ id, candidate: event.candidate })) // 发送 ICE 候选到远程终端
}
}
// 监听远程流事件
pc.ontrack = function (event) {
console.log('pc ontrack:', event)
const audio = document.createElement('audio')
audio.srcObject = event.streams[0]
audio.play()
}
ws.onmessage = async (event) => {
const data = JSON.parse(event.data)
if (data.type === 'push') {
console.log('收到 type:push 将设备增加', data.id)
clients.push({ id: data.id, channel: data.channel })
return
}
if (data.type === 'pull') {
console.log('收到 type:pull 将设备删除', data.id)
const index = clients.findIndex(client => client.id === data.id)
if (index !== -1) {
clients.splice(index, 1)
}
return
}
if (data.type === 'error') {
console.log('收到 type:error 没什么可操作的', data.id)
return
}
if (data.offer) {
const id = clients[0].id
console.log('收到 offer 并将其设置为远程描述', data.offer)
await pc.setRemoteDescription(new RTCSessionDescription(data.offer)) // 设置远程描述为 offer
await pc.setLocalDescription(await pc.createAnswer()) // 设置本地描述为 answer
ws.send(JSON.stringify({ id, answer: pc.localDescription })) // 发送给远程终端 answer
return
}
if (data.answer) {
console.log('收到 answer 并将其设置为远程描述', data.answer)
await pc.setRemoteDescription(new RTCSessionDescription(data.answer))
return
}
if (data.candidate) {
console.log('收到 candidate 并将其添加到远程端', data.candidate)
await pc.addIceCandidate(new RTCIceCandidate(data.candidate))
return
}
}
// 从文件系统中选择音乐文件
const button = document.createElement('button')
button.innerText = '选择音乐'
button.addEventListener('click', async () => {
const fileHandle = await window.showOpenFilePicker()
const file = await fileHandle[0].getFile()
const reader = new FileReader()
reader.onload = function () {
console.log('read file:', file)
const arrayBuffer = reader.result
const audioContext = new AudioContext()
// 传输音乐文件
audioContext.decodeAudioData(arrayBuffer, async audioBuffer => {
// 将音乐流添加到 RTCPeerConnection
const mediaStreamDestination = audioContext.createMediaStreamDestination()
mediaStreamDestination.stream.getAudioTracks().forEach(function (track) {
pc.addTrack(track, mediaStreamDestination.stream)
})
// 播放音乐
const audioSource = audioContext.createBufferSource()
audioSource.buffer = audioBuffer
audioSource.connect(mediaStreamDestination)
audioSource.start()
// 创建SDP offer并将其设置为本地描述, 发送给远程端
console.log('创建SDP offer并将其设置为本地描述, 发送给远程端')
console.log('clients:', clients)
const id = clients[0].id
await pc.setLocalDescription(await pc.createOffer()) // 设置本地描述为 offer
ws.send(JSON.stringify({ id, offer: pc.localDescription })) // 发送给远程终端 offer
})
}
reader.readAsArrayBuffer(file)
})
document.body.appendChild(button)
}
music()
</script>
<!--script type="module">
// 创建 RTCPeerConnection
const pc = new RTCPeerConnection()
// webSocket 连接服务器
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const host = window.location.host
const ws = new WebSocket(`${protocol}://${host}/webrtc/default`)
ws.onopen = function () {
console.log('video ws open')
}
ws.onmessage = function (event) {
const data = JSON.parse(event.data)
console.log('ws message:', data)
if (data.offer) {
console.log('收到 offer 并将其设置为远程描述')
pc.setRemoteDescription(new RTCSessionDescription(data.offer))
// 创建SDP answer并将其设置为本地描述, 发送给远程端
pc.createAnswer().then(function (answer) {
pc.setLocalDescription(answer);
ws.send(JSON.stringify({ answer }))
})
return
}
if (data.answer) {
console.log('收到 answer 并将其设置为远程描述')
pc.setRemoteDescription(new RTCSessionDescription(data.answer))
return
}
if (data.candidate) {
console.log('收到 candidate 并将其添加到远程端')
pc.addIceCandidate(new RTCIceCandidate(data.candidate))
}
}
ws.onclose = function () {
console.log('ws close')
}
setTimeout(() => {
// 获取本地视频流
navigator.mediaDevices.getUserMedia({ audio: false, video: true }).then(stream => {
// 创建本地视频元素
const localVideo = document.createElement('video');
localVideo.srcObject = stream;
localVideo.autoplay = true;
localVideo.muted = true;
document.body.appendChild(localVideo);
// 添加本地视频流到 RTCPeerConnection
stream.getTracks().forEach(function (track) {
pc.addTrack(track, stream);
});
// 监听 ICE candidate 事件
pc.onicecandidate = function (event) {
if (event.candidate) {
// 发送 ICE candidate 到远程端
ws.send(JSON.stringify({ candidate: event.candidate }))
}
};
// 监听远程视频流事件
pc.ontrack = function (event) {
// 创建远程视频元素
var remoteVideo = document.createElement('video');
remoteVideo.srcObject = event.streams[0];
remoteVideo.autoplay = true;
document.body.appendChild(remoteVideo);
}
// 创建SDP offer并将其设置为本地描述, 发送给远程端
pc.createOffer().then(function (offer) {
pc.setLocalDescription(offer);
ws.send(JSON.stringify({ offer }))
})
}).catch(error => {
console.log(error)
})
}, 1000)
</script-->
</body>
</html>