Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WebSocket for file transfer

One of my university lecturers pointed out that it would be interesting to see WebSockets used for file transfer. I'd imagine it would be possible to decode and encode an image file using base64, however would it be possible to send JavaScript / CSS files via WebSocket?

The server i'm using is Node.js, and my browser is Google Chrome 16.

like image 491
Jack Avatar asked Feb 09 '12 22:02

Jack


2 Answers

My node.js ws library handles file sends -- even binary ones. Check out one of the examples here, which does uploads: https://github.com/einaros/ws/tree/master/examples/fileapi

Rather than using websockets for receiving the webpage assets (scripts, css, images, etc), however, I'd recommend sticking with SPDY -- which was intentionally crafted for that very purpose. Node.js has spdy-support, by the way (see https://github.com/indutny/node-spdy).

like image 41
einaros Avatar answered Oct 10 '22 00:10

einaros


Yes. You can send JavaScript and CSS via WebSockets (or AJAX for that matter). You also shouldn't need to base64 encode the CSS and JavaScript like you would an image as long as the WebSocket server is properly UTF-8 encoding any special Unicode characters in the Javascript.

Once you have received the Javascript or CSS via WebSocket, you can load them using the following mechanism (where type is either 'script' or 'css'):

function dynamic_load(type, content) {
    var elem = document.createElement(type);
    elem.type = (type === 'script') ? 'text/javascript' : 'text/css';
    elem.innerHTML = content;
    document.getElementsByTagName("head")[0].appendChild(elem);
}

That mechanism may have trouble in IE 8 and earlier but since you are using WebSockets I suspect your target is modern browsers. You can verify that the dynamic_load function works from your browser's Javascript console:

dynamic_load('script', "alert('hello world');");
like image 192
kanaka Avatar answered Oct 09 '22 22:10

kanaka