发送端
<template>
<div>
<el-button style="width: 100px" @click="start">点击开始直播</el-button>
</div>
</template>
<script setup>
import { onUnmounted } from 'vue'
// 创建一个新的 WebSocket 连接
const socket = new WebSocket('ws://127.0.0.1:1800')
let mediaRecorder
// 开始直播
const start = async () => {
try {
// 请求捕获屏幕分享
const stream = await navigator.mediaDevices.getDisplayMedia({ video: true })
// 使用捕获的流创建一个新的 MediaRecorder 实例
mediaRecorder = new MediaRecorder(stream, { mimeType: 'video/webm; codecs="vp8"' })
// 当 MediaRecorder 有可用数据时触发
mediaRecorder.ondataavailable = (event) => {
// 如果数据块大小大于0且WebSocket连接处于打开状态,则发送数据
if (event.data.size > 0 && socket.readyState === WebSocket.OPEN) {
socket.send(event.data)
}
}
// 开始录制,每100ms生成一个数据块
mediaRecorder.start(100)
} catch (error) {
console.error('获取屏幕分享失败:', error)
}
}
// 当组件卸载时停止媒体录制并关闭 WebSocket 连接
onUnmounted(() => {
if (mediaRecorder) {
mediaRecorder.stop()
}
socket.close()
})
</script>
接收端
<template>
<div>
<video ref="videoElement" controls autoplay style="width: 100%"></video>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
const videoElement = ref(null)
onMounted(() => {
const socket = new WebSocket('ws://127.0.0.1:1800')
socket.binaryType = 'arraybuffer'
const mediaSource = new MediaSource()
let sourceBuffer
videoElement.value.src = URL.createObjectURL(mediaSource)
mediaSource.addEventListener('sourceopen', () => {
sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8"')
socket.onmessage = (event) => {
// console.log(event)
// 接收到数据时将其添加到 SourceBuffer
if (mediaSource.readyState === 'open' && sourceBuffer && !sourceBuffer.updating) {
// console.log(event.data)
sourceBuffer.appendBuffer(new Uint8Array(event.data))
}
}
})
onUnmounted(() => {
socket.close()
})
})
</script>
node服务器端
const WebSocket = require("ws");
// 创建一个 WebSocket 服务器实例
const wss = new WebSocket.Server({ port: 1800 });
wss.on("connection", (ws) => {
console.log("新的客户端已连接");
// 当接收到客户端发送的消息时触发
ws.on("message", (message) => {
console.log("接收到消息:", message);
// 回传消息给所有已连接的客户端
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// 当客户端连接关闭时触发
ws.on("close", () => {
console.log("客户端已断开连接");
});
// 当出现错误时触发
ws.on("error", (error) => {
console.error("发生错误:", error);
});
});
console.log("WebSocket 服务器正在监听端口 1800");
如果环境没问题,代码纯复制也没问题可以试试换个端口,最好是1100往上的端口