如何从node.js中的TCP服务器接收浏览器中的图像文件?

时间:2018-04-19 20:03:52

标签: javascript node.js tcp project

我想从TCP服务器向浏览器发送文件。基本上,我想在浏览器中打开链接时自行下载文件。

这是我的代码:

    var server = net.createServer(function(socket) {
    socket.on("error", (err) =>{
  console.log("Caught flash policy server socket error: ");
  console.log(err.stack);
});
    socket.on('end', () => {
  console.log('client disconnected');
});
    socket.on("connect", () => {
        console.log("client connected");
    });
    fs.readFile('test.jpg' , (err, data) =>{
      if(!err){
        console.log(data.length);
        socket.write(data);
      }
      else {
        console.log('readfile daemon0 err');
      }
    });
    socket.pipe(socket);
});

我总是收到错误:

6845772 //data.length
Caught flash policy server socket error:
Error: read ECONNRESET
    at exports._errnoException (util.js:1026:11)
    at TCP.onread (net.js:563:26)
client disconnected //after i disconnect

终端中没有显示“客户端连接”。

我想要做的是能够在连接时从浏览器下载此文件。我是新手,所以请帮忙!

这是完整的代码:

'use strict';

var os = require('os');
var net = require('net');
var fs = require('fs');

var PORT = 1337;

net.bytesWritten = 300000;
net.bufferSize = 300000;
//Create Server
var server = net.createServer(function(socket) {
    socket.on("error", (err) =>{
  console.log("Caught flash policy server socket error: ");
  console.log(err.stack);
});
    socket.on('end', () => {
  console.log('client disconnected');
});
    socket.on("connect", () => {
        console.log("client connected");
    });
    fs.readFile('test.jpg' , (err, data) =>{
      if(!err){
        console.log(data.length);
        socket.write("hello");
        console.log("hello");
      }
      else {
        console.log('readfile daemon0 err');
      }
    });
    socket.pipe(socket);
});

server.listen(PORT, function(){
    console.log("listen")
});

0 个答案:

没有答案