如何使用套接字发送大文件? [英] How to send large file using sockets?

查看:112
本文介绍了如何使用套接字发送大文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个zip文件(15 mb),要将其发送到android套接字连接,我可以通过以下代码发出:

i have a zip file (15 mb), want to send this to android socket connection, i can able to emit via the following code :

fs.readFile('path',function(err,fileData){
io.to(socketId).emit('sendFile',{'file':fileData.toString('base64')});
});

使用上面的代码,如果有大尺寸文件的发射被延迟,则低尺寸文件的发射没有任何延迟.如何更好地实现这一目标.

using the above code, low size file is emitting without any delay, if there is any large size file emitting is delayed. how to achieve this in a better way.

推荐答案

您可以像下面的示例一样尝试使用socket.io-stream:

You can try to use socket.io-stream like in the below example:

服务器:

'use strict';
const io = require('socket.io')(3000);
const ss = require('socket.io-stream');
const fs = require('fs');

var filename = 'test.zip';   // 80MB file

io.on('connection', function (socket) {
  console.log('client connected');
  socket.on('sendmeafile', function () {
    var stream = ss.createStream();
    stream.on('end', function () {
        console.log('file sent');
    });
    ss(socket).emit('sending', stream); 
    fs.createReadStream(filename).pipe(stream);
  });  
});

console.log('Plain socket.io server started at port 3000');

客户端:

'use strict';
const socket = require('socket.io-client')('http://localhost:3000');
const ss = require('socket.io-stream');
const fs = require('fs');

var filename = 'test-copy.zip';

socket.on('connect', function () {
  console.log('connected');
  socket.emit('sendmeafile');
});

ss(socket).on('sending', function(stream) {
  stream.pipe(fs.createWriteStream(filename)); 
  stream.on('end', function () {
    console.log('file received');
  });
});

正如jfriend00在他的评论中写道,您不需要http.

As jfriend00 wrote in his comment you don't need http.

这篇关于如何使用套接字发送大文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆