Websockets or AJAX or both? - ajax

I am a bit confused about how one uses websockets. I have already set up a websocket server and are able to receive from server and send to server.
My question is. When using websockets, are you supposed to drop the ajax part completely? Or are you supposed to use websockets alongside ajax?
Example:
I want to use websockets on a chat service on a website where users can log in. When logging in, I use ajax. When on the message page I use websockets to receive future messages, and send future messages. But when navigating to the messages page, I use ajax to get the messages from database.
Is this the correct way of using websockets? Or should I do everything in websockets since 1 user 1 active connection is more efficient? Or should 1 user have 1 websocket connection, but still keep sending ajax requests to the server when navigating to some pages without reloading the site, using ajax?
What is the best practice when creating a large application where users can log in, navigate to pages to load stuff async, but still wanting that bidirectional real time benefits of websockets on stuff like messaging services and notification services on that same website?

There is no reason you cannot use both. I think the solution depends on what server side resources you are using. I may need access to a server through websockets to get updates to a chat dialogue. I may use a completely different system to get user statistics or provide authentication.
I don't think there is a specific answer to your question as it varies depending on the application in question.

Related

Can the Server tell the Client to refresh the page?

I have a Client that tell my server to contact another server and save the data there upon saving if successful I can receive a callback, how can I then tell the Client to refresh the page because this 2nd Server is also sending data to the Client, can I do it using headers?
There is no tranditional ways to push messages (refresh request and so on) to the webpage directly from the server.
Before giving some solutions, I'm sorry to say that your description to your question is quite ambiguous. server, another server, this 2nd Server is also sending data to the Client does not make much sense. You may reorganize your description to show the whole business logic better. Giving necessary code will be better.
So focusing on sending message from server to client within browser environment, there are several ways you could consider:
Ajax
You could use ajax to request the server at client side. You can poll the server at regular intervals, checking the response to determine whether the page should be refreshed.
Pro: widely supported, easy for both client side and server side
Con: polling is not a real-time solution and will make some redundant requests
Websocket
Pro: real-time bidirectional socket-like communication
Con: may be too heavy for the simple task you mentioned
Server push
Part of PWA specification
Pro: allow direct communication from server to client
Con: complexity, insufficient browser support

Should I use web sockets to pull data from server or just a flag and use that flag to send API request for data?

I am working on a project which is basically a Customer Feedback Analysis Dashboard. There are few graphs on the dashboard and data for each graph is fetched from the server through API requests.
Right now the dashboard is updated every time the page is refreshed. I want it to be updated immediately when there is a new feedback in the system. I am confused, whether I use websockets to send data for each graph or just a flag and use that flag to fetch data through API requests.
Like, facebook/twitter does. They tell you about new posts/tweets and when you click that button your feed/wall gets updated.
If you want to "push" data from server to client and you want that data to show up in a timely fashion (e.g. within 10-20 seconds of when it was available on the server), then you will want to implement some sort of "push" solution where the server can efficiently push data to the client whenever there is new data to send.
There are several possible approaches:
webSockets
socket.io
Server-sent events
Mobile platform-specific push (Android and iOS)
For a general purpose solution that works within a browser, you will want to use one of the first three. socket.io is built on top of webSockets (it just adds more features) so architecturally, they are similar.
Server-sent events are fairly new (modern browsers only) and are only for one way communication (from server to client). webSockets can be used for communication either way.
I'd personally recommend socket.io because of the features it offers (such as automatic client reconnection) and a simplified messaging layer. You can see the feature difference between socket.io and webSockets here. With socket.io, the client makes a connection to the server when the web page is loaded and that connection is persistent. After the connection is established, then either client or server can send messages to the other at any time in a very efficient manner.
Other useful references:
Push notification | is websocket mandatory?
websocket vs rest API for real time data?
Why to use websocket and what is the advantage of using it?
What are the pitfalls of using Websockets in place of RESTful HTTP?
Ajax vs Socket.io

When to use socket.io and when to use ajax

I have been programming in nodejs have looked at how to use both socket.io and ajax calls to the node server. Is socket.io designed to replace ajax? I am curious to know in which cases it is good to use socket.io and which ones ajax is nicer. Thanks for the input.
Well, one of the main thing web sockets (via socket.io) provides that ajax lacks is server push. So with ajax if you want to find out about new events on the server (a different user sent you a message, for example), you need to do server polling, meaning you send ajax requests in a relatively frequent periodic loop. Most of the time the server responds that there's nothing new, but occasionally when there is something new, the client can learn about it.
Web sockets allow the server to actively push notices to the client without polling. So if your application has any kind of information that needs to start on the server and just show up in the browser, web sockets are a better solution there.
Submitting data to the server in request/response model
ajax or web sockets essentially equivalent, traditional form POSTS also OK
Submitting events to the server in an event stream model
web sockets are best, can be emulated via ajax somewhat
Pushing events from server to browser
web sockets are best, can be emulated via ajax long polling, flash, etc (socket.io has several fallbacks it can try to use if real web sockets are not available).
older browsers, some mobile platforms
web socket support is not there, so ajax is your fallback

Websockets (Socket.io) and authentication/authorization

I'm giving socket.io a whirl and I'm curious as to what I should and shouldn't be doing with websockets.
For example is there a way to authenticate a websocket (include id in every message perhaps?)? Let's say I'm creating a 'google docs' like app in which people can create new documents. Should I be using AJAX to create new documents instead of websockets? That way I can use the standard HTTP transport layer to do all of the user authorization (checking session, etc) and then simply ping back the page with a websocket event. Curious as to how people handle situations like this.
I would recommend using AJAX wherever you do not absolutely need web sockets. Web sockets end up creating more load on the server side (socket.io will take care of fallbacks in case web sockets & flash sockets are not available). In short, use web sockets where you need to maintain that state/connection to the client.
If you wish to use web sockets, using cookies with socket.io would be one approach that would allow you to keep track of your sessions. If not using socket.io right away, you can send req.sessionID (key) to the client, store the session information in Redis/Mongo etc. When the socket.io connection is attempted, read the cookie value & send it to the server - where you can get the session store information. There may be issues if you use flash sockets as one of the fallbacks.
Hope this helps.

Ajax vs Comet (not a chat application)

I've developed a web-based application in which a signed in user should send a message to the server telling he is still online every 3 seconds. The message is then processed by the server and a stored procedure is called in Mysql to set the user's status to online.
I've looked in to similar issues in which Comet and Ajax are compared (here or here) but considering that 3 second delay is acceptable and maximum users of 1000 are online in the system, is using Ajax a wise choice or Comet should be used?
For this kind of feature comet is more appropriate:
Your clients send messages (i'm online)
Your server broadcast the processed message (user X is still online)
In an ajax way you are only serving messages to server.
In order to get the "broadcast effect" in an ajax way. You will end up doing something similar to comet but with less efficient bandwidth.
Ajax:
Client send server - i'm in
Server process
Server send back to client list of user in.
In this case every client ask every 3 second the database for the COMPLETE "in" list.
In comet:
Client X send server - i'm in
Server process
Server send back to client S that user X is still online
In this case every client tell the server every 3 second that he is in.
The server send back to every connected client ONLY that x is still in
Comet is just the technique to broadcast back and push messages to client
Ajax is the technique to push client information to the server without having to refresh all the page.
Quoting wikipedia:
http://en.wikipedia.org/wiki/Comet_%28programming%29
Comet is known by several other names, including Ajax Push, Reverse Ajax , Two-way-web, HTTP Streaming,and HTTP server push among others.
So go comet :)
If you do not broadcast anything, then simple Ajax is the best option
In this particular case, since you do not need to send any information from the server to the client(s), I believe Ajax is the more appropriate solution. Every three seconds, the client tells the server it is connected, the database is updated, and you're done.
It could certainly be done using Comet, in which case you would basically ping each registered client to see if it is still connected. But, you would still need to run a query on the database for each client that responds, plus you would still need the client to notify the server on its initial connection. So, it seems to me that Comet would be more trouble than it's worth. The only thing that might make sense is if you could ping each registered client and store the responses in memory, then once all clients have been pinged you can run one single query to update all of their statuses. This would give you the added bonus of knowing as soon as a client disconnects as opposed to waiting for a timeout. Unfortunately, that is beyond the scope of my expertise with Comet so, at this point, I can't help to actually implement it.

Resources