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 badges2 Answers
Reset to default 8Yes. 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
版权声明:本文标题:javascript - Using WebSocket for file transfer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741289134a2370446.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论