admin管理员组

文章数量:1277316

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.

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.

Share Improve this question asked Feb 9, 2012 at 22:50 JackJack 15.9k20 gold badges70 silver badges93 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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

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

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

本文标签: javascriptUsing WebSocket for file transferStack Overflow