Using WebSocket to transfer files

One of my university teachers noted that it would be interesting to see the WebSockets used to transfer files. I would suggest that it would be possible to decode and encode the image file using base64, however could I send JavaScript / CSS files via WebSocket?

The server I use is Node.js and my browser is Google Chrome 16.

+6
source share
2 answers

Yes You can send JavaScript and CSS via WebSockets (or AJAX, for that matter). You also do not need base64 to encode CSS and JavaScript in the same way as an image if the WebSocket server correctly encodes UTF-8 any Unicode special characters in Javascript.

After you get Javascript or CSS via WebSocket, you can load them using the following mechanism (where type is "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); } 

This mechanism may have problems in IE 8 and earlier, but since you are using WebSockets, I suspect that your goal is modern browsers. You can check if the dynamic_load function works from the Javascript browser console:

 dynamic_load('script', "alert('hello world');"); 
+8
source

My node.js ws library handles sending files - even binary ones. Check out one example here that downloads: https://github.com/einaros/ws/tree/master/examples/fileapi

Instead of using websockets to get web page resources (scripts, css, images, etc.), I would recommend sticking with SPDY, which was specially created for this purpose. node.js has spdy support, by the way (see https://github.com/indutny/node-spdy ).

+1
source

Source: https://habr.com/ru/post/908104/


All Articles