简体   繁体   English

使用WebSocket进行文件传输

[英]Using WebSocket for file transfer

One of my university lecturers pointed out that it would be interesting to see WebSockets used for file transfer. 我的一位大学讲师指出,看到WebSockets用于文件传输会很有趣。 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? 我想可以使用base64对图像文件进行解码和编码,但是可以通过WebSocket发送JavaScript / CSS文件吗?

The server i'm using is Node.js, and my browser is Google Chrome 16. 我正在使用的服务器是Node.js,我的浏览器是Google Chrome 16。

Yes . 是的 You can send JavaScript and CSS via WebSockets (or AJAX for that matter). 您可以通过WebSockets(或AJAX)发送JavaScript和CSS。 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. 只要WebSocket服务器正确地对Javascript中的任何特殊Unicode字符进行UTF-8编码,您也不需要像对图像一样对CSS和JavaScript进行base64编码。

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'): 一旦通过WebSocket接收到Javascript或CSS,就可以使用以下机制加载它们(其中type是'script'或'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. 在IE 8及更早版本中,该机制可能有问题,但由于您使用的是WebSockets,我怀疑您的目标是现代浏览器。 You can verify that the dynamic_load function works from your browser's Javascript console: 您可以从浏览器的Javascript控制台验证dynamic_load函数是否有效:

dynamic_load('script', "alert('hello world');");

My node.js ws library handles file sends -- even binary ones. 我的node.js ws库处理文件发送 - 甚至是二进制文件。 Check out one of the examples here, which does uploads: https://github.com/einaros/ws/tree/master/examples/fileapi 看看这里的一个例子,它上传了: 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. 然而,我不建议使用websockets接收网页资产(脚本,CSS,图像等),而是建议坚持使用SPDY - 这是为了这个目的而故意制作的。 Node.js has spdy-support, by the way (see https://github.com/indutny/node-spdy ). 顺便说一句,Node.js有spdy支持(参见https://github.com/indutny/node-spdy )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM