从服务器向客户端发送图像的最有效方法是什么?

时间:2019-02-11 20:58:38

标签: node.js image websocket

我已经用express创建了一个node.js服务器和一个网站。该站点主要用于显示相关图片的负载,例如2017年拍摄的照片。服务器在Raspberry pi上运行,并连接有外部HDD,服务器从中获取图像。当用户访问站点时,客户端通过websocket向服务器发送启动请求以开始发送图像。然后,服务器也通过websocket发送X个图像,并且用户可以通过另一个启动请求来请求更多图像。如何提高效率?有没有比websockets更快的方法?

一些评论

  1. 我知道Pi本身就很慢,而HDD是瓶颈。但是,我想优化数据传输。
  2. 我已经在另一个问题中研究了堆栈溢出问题,它建议剥离已经完成的元数据。

服务器端代码:

con.on("message", function incoming(message) {

  let msgArr = message.split(", ");
  let prefix = 'a';
  let year = '2008';

  if (msgArr[0].includes('2008')) {prefix = 'a'; year = '2008'}
  if (msgArr[0].includes('2009')) {prefix = 'b'; year = '2009'}
  if (msgArr[0].includes('2010')) {prefix = 'c'; year = '2010'}
  if (msgArr[0].includes('2011')) {prefix = 'd'; year = '2011'}
  if (msgArr[0].includes('2012')) {prefix = 'e'; year = '2012'}
  if (msgArr[0].includes('2013')) {prefix = 'f'; year = '2013'}
  if (msgArr[0].includes('2014')) {prefix = 'g'; year = '2014'}
  if (msgArr[0].includes('2015')) {prefix = 'h'; year = '2015'; msgArr[1]++;}
  if (msgArr[0].includes('2016')) {prefix = 'i'; year = '2016'; }
  if (msgArr[0].includes('2018')) {prefix = 'j'; year = '2018';}


  let path = "/Volumes/Seagate\ Drive/" + year + "/" + prefix + msgArr[1] + ".jpg";

fs.readFile(path, function (err, data) {
  if (err) {con.send("error")}
  else {
    con.send(data.toString('base64'));
    console.log("image sent");
  }

客户端只接收图像,将其放置在站点上,然后再发送一幅图像的请求,直到达到X幅图像为止。

1 个答案:

答案 0 :(得分:0)

希望这会有所帮助

const path = require("path");
const fs = require('fs');

exports.getBookImage = async (req, res) => {
    let filepath = path.join(__dirname + `/root/folder/file`);
    res.sendFile(filepath);
};

这里__dirname是一个内置函数,用于获取要执行的当前文件的路径