用代码实现websocket从服务器向前端发送视频图片文档信息
时间: 2024-03-21 16:40:26 浏览: 28
这里给出一个基于Node.js和ws库的例子,实现WebSocket从服务器向前端发送视频、图片、文档等信息:
```javascript
// 服务器端代码
const WebSocket = require('ws');
const fs = require('fs');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
// 发送视频信息
const videoStream = fs.createReadStream('video.mp4');
videoStream.on('data', (data) => {
ws.send(data, { binary: true });
});
// 发送图片信息
const imageStream = fs.createReadStream('image.jpg');
let imageData = '';
imageStream.on('data', (data) => {
imageData += data.toString('base64');
});
imageStream.on('end', () => {
ws.send(JSON.stringify({ type: 'image', data: imageData }));
});
// 发送文档信息
const documentData = { title: 'Sample Document', content: 'This is a sample document.' };
ws.send(JSON.stringify({ type: 'document', data: documentData }));
});
// 前端代码
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('WebSocket connected');
};
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.type === 'image') {
const img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + message.data;
document.body.appendChild(img);
} else if (message.type === 'document') {
const title = document.createElement('h1');
title.innerText = message.data.title;
const content = document.createElement('p');
content.innerText = message.data.content;
document.body.appendChild(title);
document.body.appendChild(content);
}
};
const video = document.createElement('video');
video.controls = true;
document.body.appendChild(video);
ws.binaryType = 'arraybuffer';
ws.onmessage = (event) => {
const buffer = event.data;
const videoBlob = new Blob([buffer]);
const videoUrl = URL.createObjectURL(videoBlob);
video.src = videoUrl;
};
```
这个例子中,服务器端使用Node.js和ws库创建WebSocket服务,并在客户端连接上来时,分别发送视频、图片、文档信息给客户端。客户端使用WebSocket API创建WebSocket连接,并在接收到服务器发送的消息时,根据消息类型分别处理视频、图片、文档信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)