Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io chat app that can also send image and even file

I've been interested in the Socket.io project recently and I wonder if there's easy way to send image or even other type of files without having to use other library. I'm not trying to upload the file to the server to store, I just want to broadcast it to those who are in the chat room at that moment. So the code should be minimal. However I'm really bad at encoding/decoding stuff, so some example code would be great.

like image 462
soloway Avatar asked Jan 18 '16 08:01

soloway


People also ask

Which is better Socket.IO or WebSocket?

Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more. So it is not just a wrapper, it is full-featured library.

Is Socket.IO full duplex?

info. WebSocket is a communication protocol which provides a full-duplex and low-latency channel between the server and the browser. More information can be found here.

Is Socket.IO and WebSocket same?

Socket.IO is built on top of the WebSocket protocol and provides additional capabilities such as automatic reconnections, broadcast support, or falling back to HTTP long polling. Note that Socket.IO uses Engine.IO under the hood to establish the low-level connection and exchange data between client and server.


1 Answers

I've adapted the official chat example of Socket.io and added functionality of sending file/images and even videos through base64 encoding, you can have a look at the source code in client.js and index.js, below are the most relevant part, hope it's helpful to you.

On client side:

$('#uploadfile').bind('change', function(e){
    var data = e.originalEvent.target.files[0];
    readThenSendFile(data);      
});

function readThenSendFile(data){

    var reader = new FileReader();
    reader.onload = function(evt){
        var msg ={};
        msg.username = username;
        msg.file = evt.target.result;
        msg.fileName = data.name;
        socket.emit('base64 file', msg);
    };
    reader.readAsDataURL(data);
}

On server side:

socket.on('base64 file', function (msg) {
    console.log('received base64 file from' + msg.username);
    socket.username = msg.username;
    // socket.broadcast.emit('base64 image', //exclude sender
    io.sockets.emit('base64 file',  //include sender

        {
          username: socket.username,
          file: msg.file,
          fileName: msg.fileName
        }

    );
});

Here's the project:

https://github.com/Arch1tect/Chatbox

like image 96
Arch1tect Avatar answered Sep 21 '22 06:09

Arch1tect