【发布时间】: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