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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With