I am developing a small app in Node.js with a MongoDB database, I have nginx in front to handle static files and the initial index.html.
When I visit my index.html all the javascript/css/img files are loaded, and a websocket connection is made to the node.js server.
Initially my index.html is empty, it needs to be filled with the right template file. One thing I could do is do a normal ajax req.
$.get('myfile.html') and append it to my content. The websocket just handles the database data.
Now I already have an open websocket connection the server, why don't I just transfer the .html template along with the data from the database, and merge it in the client.
The template files are just little html snippets, why waste a http req, right??
Note that this app will only be used by selective people with full html5 browser support. No fallback situations are required.
Avoid using WebSockets if only a small number of messages will be sent or if the messaging is very infrequent. Unless the client must quickly receive or act upon updates, maintaining the open connection may be an unnecessary waste of resources.
Sending Messages With WebSocket You can send both text and binary data through a WebSocket. For your demo application you need to send the contents of the textarea to the server when the form is submitted. To do this you first need to set up an event listener on the form.
It has built-in means of detecting transmission errors or packet corruption and attempting retransmissions in those cases, but delivery can still fail. It guarantees that if the packet is not delivered, the caller will get an error so the caller can know. Since websocket is built on top of TCP, it has the same issue.
WebSocket solves a few issues with HTTP: Bi-directional protocol — either client/server can send a message to the other party (In HTTP, the request is always initiated by the client and the response is processed by the server — making HTTP a uni-directional protocol)
Given that HTTP is so well suited for serving files, with caching -- potentially in several layers -- working for you so you won't even have to send any html content more than once to a visitor, I definitely think the upsides outweighs the downsides. It sounds like you could send an index.html along with related content, and have the templates in your index.html (e.g. as in jQuery templates which can use a <script id="fooTemplate" type="text/x-jquery-tmpl">
tag).
Obviously you can send the templates over a WebSocket.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With