【问题标题】:How to let client receive image through the tcp?如何让客户端通过 tcp 接收图像?
【发布时间】:2021-08-23 14:41:32
【问题描述】:
**server** 

const net = require("net");
const fs = require("fs");
const server = net.createServer();

server.on("connection", (client) => {
  client.setEncoding('utf8');
  
  console.log("New client connected!!!");
  
  client.write('Hello there!');
  
  client.on('data', (data) => {
    console.log('Message from client: ', data);
    fs.readFile('./image/image.jpeg' , (err, data) =>{
      if(!err){
        console.log("Image has been sent!");
        client.write(data);
      }
      else {
        console.log('readfile error!');
      }
    });
  });
  
})

server.listen(3000, () => {
  console.log('Server listening on port 3000!');
});

我正在尝试将图像从服务器发送到客户端。我收到“图片已发送!”服务器端的消息,但未能将此图像存储到本地主机。我想知道是什么导致了这个问题,以及如何解决它。我是初学者。感谢您耐心的教导和时间!

**client**
const net = require("net");
const fs = require("fs");

const conn = net.createConnection({
  host: "2.tcp.ngrok.io",
  port: 15258 
});

conn.setEncoding("utf-8");

conn.on('connect', () => {
  console.log("connect from client");
  conn.write('Hello from client!');
});

conn.on('data', (data) => {
  fs.writeFile("./image/pikaqu.jpeg", data, (error) => {
    if (!error) {
      console.log("Image has been stored!");
    } else {
      console.log("writeFile error!")
    }
  })
});

There is the output of client side terminal.   
 5�nⶪǻ��N���ۣ�d����B�
                       ��l^Ni5]����]`�p��̖Wi�6�QATa[t���1���u��|U�>g�׍�ѻ����=?IEw�X���C'b�;�Vy�����
    � �l���w�L�uuRo�S*�W=�Zi�K4N�JQ�N��7%�o��NyNRylE�Z���U_;�f
    Image has been stored!
    Image has been stored!

【问题讨论】:

  • data 事件只是一个传入的数据块。您很可能会收到多个data 事件,您的接收代码会将第二个数据事件的数据写入文件中第一个数据事件的数据之上。相反,您需要累积所有数据并以正确的顺序将其全部写入文件。或者在文件到达时将其流式传输到文件中,将每个新文件附加到文件末尾。
  • 另外,使用原始 TCP 没有协议来标记图像数据的开始和结束。你需要自己发明一种方法来做到这一点。通过让客户端发出 http 请求并让服务器发送图像以响应传入的 http 请求,这可能会更好地完成。那么,协议已经为你设计好了(http)。

标签: javascript node.js networking tcp


【解决方案1】:

试试这个:

fs.writeFile("./image/pikaqu.jpeg", data, (error) => {

【讨论】:

  • 我还有 2 个问题。 ./ 和 / 有什么区别?我实际上收到了该图像已存储在终端上,但终端的输出是 5�nⶪǻ��N����d����B���l^Ni5]����]`�p ��̖Wi�6�QATa[t���1���u��|U�>g�׍�ѻ����=?IEw�X���C'b�;�Vy�� ����������w�L�uuRo�S*�W=�Zi�K4N�JQ�N��7%�o��NyNRylE�Z���U_;�f 图像已存储!图片已保存!图片已保存!这里实际发生了什么?
  • "./" 是当前路径 "/" 是根路径。
猜你喜欢
  • 2012-03-15
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2014-08-26
  • 1970-01-01
相关资源
最近更新 更多