Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send large file using sockets?

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.

like image 779
midhun k Avatar asked Feb 06 '23 19:02

midhun k


1 Answers

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

server:

'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');

client:

'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');
  });
});

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

like image 160
mk12ok Avatar answered Feb 08 '23 10:02

mk12ok