Ajax or Websockets for small transmissions - javascript

Im building a Chat website that uses Websockets(Socket.io) to send and receive messages to the server. In fact my website should use Websocket and now my problem is that for other transmissions like checking username at login or fetching JSON and updation DOM and other stuff, Can i use the same technology(Websockets) or i have to use Ajax? i know that in Websockets way, server and client will have a persistant connection.
What is the best way? Using Websockets is not good for these purposes? Why?

You can use websockets. The difference is with websockets the client is always connected. You'll have a handler that handles messages (which could be just json blobs maybe with some kind of messageType field) as they stream in from the client.
This means the server side handling is basically the same except instead of serving your responses via over different HTTP request (via different routes), you dispatch the request to the appropriate handler by something not much more complicated than a switch statement. Any results are then sent back to client over the websocket which has a similar handling mechanism.
One downside is not all browsers support websockets so if you need to support a fallback path to JSON then it's certainly easier to use the fallback JSON handlers for the aux requests (since you'll be writing them anyway).
Otherwise the differences are probably marginal. I'd be more concerned about code cleanliness.

Related

Node.js chat without Socket.IO

I just started learning Node.js and as I was learning about the fs.watchFile() method, I was wondering if a chat website could be efficiently built with it (and fs.writeFile()), against for example Socket.IO which is stable, but I believe not 100% stable (several fallbacks, including flash).
Using fs.watchFile could perhaps also be used to keep histories of the chats quite simply (as JSON would be used on the spot).
The chat files could be formatted in JSON in such a way that only the last chatter's message is brought up to the DOM (or whatever to make it efficient to 'fetch' messages when the file gets updated).
I haven't tried it yet as I still need to learn more about Node, and even more to be able to compare it with Socket.IO, but what's your opinion about it? Could it be an efficient/stable way of doing chats?
fs.watchFile() can be used to watch changes to the file in the local filesystem (on the server). This will not solve your need to update all clients chat messages in their browsers. You'll still need web sockets, AJAX or Flash for that (or socket.io, which handles all of those).
What you could typically do in the client is to try to use Web Sockets. If browser does not support them, try to use XMLHttpRequest. If that fails, fallback to Flash. It's a lot of programming to do, and it has to be handled by node.js server as well. Socket.io does that for you.
Also, socket.io is pretty stable. Fallback to Flash is not due to it's instability but due to lack of browser support for better solutions (like Web Sockets).
Storing chat files in flatfile JSON is not a good idea, because if you are going to manipulating the files, you would have to parse and serialize entire JSON objects, which would become very slow as the size of the JSON object increased. The watch methods for the filesystem module also don't work on all operating systems.
You also can't compare Node.js to Socket.IO because they are entirely different things. Socket.IO is a Node module for realtime transport between the browser and the server. What you need is dependent on what you're doing. If you need chat history, then you should be using a database such as MongoDB or MySQL. Watching files for changes is not an efficient way and you should just send messages as they received.
In conclusion no, using fs.watchFile() and fs.writeFile() is a very bad idea, because race conditions would occur due to concurrent file writes, besides that fs.watchFile() uses polling to check if a file has changed. You should instead use Socket.IO and push messages to other clients / store them in a database as they are received.
You can use long pooling method using javascript setTimeout and setInterval
long pooling
basically long pooling working on Ajax reqest and server responce time.
server will respond after a certain time (like after 50 seconds ) if there is not notification or message else it will respond with data and from client side when client gets response client javascript makes another request for new update and wait till response this process is endless until server is running

Is there a standard for converting a WebSocket request into an HTTP request on the server?

I'm pretty new to WebSockets and this may be completely insane. If so, please let me know what I should be doing instead.
The idea is that I'd like to have a WebSocket connection in the browser that ultimately interfaces with a database. Because the db shouldn't be exposed to the browser there would be, of course, a server layer in between that takes in the WebSocket message and then converts that into something like a POST, or DELETE request. The server would then pass that message along to the database.
So the question is: Is there some kind of standard for translating WebSocket messages into HTTP requests?
I found one blog post where the guy made sure his WebSocket messages from the browser came in the form {"method":"POST","content":"foo"} so they could be understood with normal JSON parsing. Is something like this ok or is there a more acceptable "right way."
Something like this is not only ok, it is the only way. You need a protocol in order to communicate between server and client (otherwise how would a server/client understand what you want from it?). Whatever you choose it will be fine (you can even use standard HTTP over WebSockets). Creating your own protocol (like with the example you came up with) is perfectly fine as well. I prefer JSON-based protocols because it is easy to work with them (JSON parsers are built-in or easily available in most known lanugages)

Is it bad to use socket.io for most of the requests or should I only use it to push data to client?

Is it bad to replace AJAX routes (called with $.Ajax from jquery) such as:
GET /animals
GET /animals/[id]
POST /animals
With socket.io events (event binded on client and server so the client can have a response):
emit("animals:read")
emit("animals:read", {id:asdasd})
emit("animals:write", animalData)
or should I "only" use socket.io it to push data to client?
[EDIT]
I could see one problem if I don't use socket io for my POST route. The problem is that I can't easely use the client's socket to broadcast data:
Server:
on("animals:write", function(data){
saveAnimal(req.data)
socket.broadcast(...)
emit("animals:write", writenAnimal)
})
VS
app.post(function(req,res){
saveAnimal(data)
// cant broadcast :(
res.send(201,writenAnimal)
})
I will push data to clients in some other requests for sure, so all clients will have at least 1 socket.
IMHO socket.io should be used if you want real-time data provided for your website. Take for example Stackoverflow. It uses websocket to update in realtime your scores and update your notifications.
But if you really want to create application that is SEO-friendly ( I mean supporting http for serving your pages ) and more important if you are aware of the difficulties in managing sessions and permissions in socket.io, I think you'll prefer AJAX for your pages and socket.io for other realtime data.
I would use ajax for this, its http based data requests, nothing realtime.
If you don't want to push data to the client, I don't see why you would use socket.io instead of AJAX. I mean with AJAX you don't need to handle a session with the client and it would probably scaled better.
With socket.io, for every connected client you need some sort of object on the server paired up with that one client. It will use more memory on the server for no reason if permanent connections are unnecessary or unwanted.
Also, AJAX will be better if you want to re-use your code with other systems, it is working with a huge existing ecosystem of tools.
That being said, if you need WebSocket features like pushing the data to the client or doing some kind of broadcast, you might consider using socket.io instead of AJAX since it will be hard to achieve this with AJAX and socket.io offers those features.

Can I keep pushing data from the server to the same connection?

I'm setting up a stock-ticker like web-page, written in JavaScript. I am also writing the server that the page talks to, in C++.
I would like to make the web page efficient, such that it makes sends single subscription message to the app server, and then holds a keep-alive connection open, constantly receiving inbound data pushed from the app server.
At the moment, I have to re-issue the web clients' subscription call every time I receive data from the server. The problem is that each time the XHR object hits readyState(4), the call is effectively completed. Any data arriving at the web page after this is ignored. The web-client can resend data and that resets the object, but the send is unnecessary, and is only being used to reset the XHR object.
I would like to know if it is possible to somehow reset the existing XHR object, and put it into a state where it expects more inbound data, so that when more data is pushed to the web page, the web page responds and processes it.
Thanks in advance for any help you can give. Note: Not using JQuery on this project.
I highly recommend looking into Websockets, especially a library like socket.io, which encapsulates various browser's implementations of Websocket transports into a single API (WS, JSON, JSONP, Flash and Long Polling).
Socket.io client libraries should be now be supported by all major browsers. Your only challenge might be locating a C++ specific server implementation. Hopefully this SO question might be of some help
Otherwise, your only other option is long-polling or comet on the client with a suitable server-side implementation that would scale (i.e. something like an event driven server like NginX as opposed to a thread-per-connection architecture.)
I do appreciate that you are committed to C++ but my humble advise would be to investigate Node.js as it can and does provide a very performant solution with very little effort.
HTH and all the best.
HTTP is a one-off protocol: one request, one response, and you're done. If you want to keep a connection open, you can use Websockets (MDN reference page, client-side code example). However consider it won't be supported on older browsers (IE, for example, just started supporting Websockets on version 10), so you'll probably need to implement a fallback using XHR and long-polling.

Using Node.js to track XMLHTTPRequests

I've just started learning Node.js and was very interested in its real-time capabilities, especially with Socket.io. Since then, I've written a very basic script to connect to Twitter's streaming server and broadcast tweets to all connected clients.
To build that, I used http.createClient to connect to stream.twitter.com and added in the relevant response and data event handlers. Everything works quite well.
Obviously, Twitter's Streaming API pretty much outputs an infinitely loading webpage and what why using a data event handler works fairly well with it. However, is it possible to make other types of websites 'streamable'?
For example, if a client (browser) updates a website periodically using an XMLHTTPRequest, would it be possible to track the output of those requests using the HTTP API of Node.js? Or similar Node.js extension?
Thanks.
websites do not periodically use XMLHTTPRequest. Clients periodically send XMLHTTPRequests to an URL.
A simple call to http.request(options, callback) with the correct headers should emulate XHR's. Most of these servers will also accept normal POST or GET requests.
If you want node.js to connect to a server and simulate a browser then something like zombie would serve you well. It claims to support XMLHTTPRequest.
The best case for you would be to use web-sockets between your dashboard and node server. This way node will be notified immediately that something has updated at your dashboard ( I am assuming that you can modify your dashboard a bit to accept such connections, won't be difficult as long as you have access).
Then you can use long polling at client-end i.e. send a request to the node server and wait. Node will receive the request and then register an event to it. The moment it receives the updates from dashboard, it'll fire the event which will send the response to all the clients one by one waiting.
I would recommend take a look at http://github.com/andrewdavey/vogue . It does something similar but the functionality is ofcourse different.

Categories

Resources