AJAX in chat applications - node.js

When I read about how to create chat applications in Node.js, I found out that the recommended way to do so was to use Socket.io and websockets.
I also read that we can regularly send requests using AJAX and wait for responses from the server.
So my question is: Can AJAX serve the same purpose as WebSockets, and use AJAX for chat applications instead of WebSockets?

You don't have to use websockets for chat applications, there is actually a wide range of technologies you can use.
AJAX: AJAX, or long polling can be used for web chats, but is considered a primitive and inefficient way to get updated chat information. The client listens for a change on the server-side, then when it get's a response from the server, it then makes another request to listen for requests. The reason this is looked down upon is because they client could be listening for a long time, without a response from the server.
WebSockets: Websockets is a protocol that runs over HTTP that facilitates bi-directional data. Similar to the TCP websocket protocol, there is a 3-way handshake involved in order to make a connection. Socket.io aids in the use of websockets by abstracting a lot of the raw websocket functions. The truth is that Socket.io actually provides backwards compatibility with browsers that only support long-polling or Flash for chat communication. Unlike WebRTC, there is a man-in-the-middle (server) to facilitate who is chatting with who.
WebRTC: WebRTC is a free, open project that provides browsers and mobile applications with Real-Time Communications (RTC) capabilities via simple APIs. These protocols allow peer-to-peer communications (chat included) with little use of a middle-man, or server. To address your question, it's great for "private-chats".
Flash: It is possible to use Flash for chat communications over the web. This is severely outdated, as Flash is slowly dying from the web.

Related

chat application, peer-to-peer communication

I am in the process of developing a chat application using Javascript. When sending messages from one client to another client, do I have to send it through a server or can I send it directly from a peer-to-peer approach, using something like websockets ?
Welcome to the stage of life where you see the importance of design patterns.
You can start solutionizing with mediator pattern and proxy pattern with web sockets.
Wheater you need a server or not is up to your design.
Technology-wise there are multiple APIs that HTML5 offers you can go through them and make something on your own.
There is a bunch of APIs available with HTML5 and JS.
Start digging on WebSockets, Server-Sent Events, Web Workers.
The server will give you the flexibility of record-keeping while acting as a mediator. Alternatively, you can come up with a pure p2p design with a scheme where every node or user notify other users with their details(IP) for establishing communication. Remember for web socket to work the client need to know what address to connect to. Maybe it can have fixed master nodes. Then you can use observables for polling and other features. Take a look at the BitTorrent protocol for design inspiration.
Get creative and start designing.
There are many ways to do it. I recommend the scheme:
Peer <---> custom websocket server <---> Peer;
I recommend NodeJS with SocketIO.

Nodejs: SocketIO (websockets) vs Http

Normally i use ajax http requests to get/post data. Now i have thoughts like why shouldn't i replace all the ajax get requests with socketIO?is there any disadvantage in following this approach?
I understand that session cookies via http headers will be sent between client and server during every http requests, during client<=>server interactions using sockets, will the session cookies in browser automatically sent to the server via socket headers(if that exists)?
In which usecases should i prefer SocketIO over Http?(if you consider this as a question that demands broad answer then you can link me to some relevant articles)
WebSockets are useful when the server needs to push some real time information to the client about some events that happened on the server. This avoids the client making multiple polling AJAX calls to verify if some event has occurred on the server.
Think of a simple chat application. If the client needs to know if the other participant in a chat session has written something in order to display it, he will need to make AJAX calls at regular intervals to verify this on the server. On the other hand WebSockets allow the server to notify the client when this even occurs, so it is much more efficient in terms of network traffic. Also the WebSockets protocol allows the server to push real time information to multiple subscribed clients at the same time: for example you could have a web browser and mobile application subscribed to a WebSocket and talking to each other directly through the server. Using AJAX those kind of scenarios would be harder to achieve and would require much more stateless HTTP calls.
I understand that session cookies will be sent between client and server during every http requests, is this case the same during client<=>server interactions using sockets
The WebSockets protocol is different from the HTTP protocol. So after the initial handshake occurs (which happens over HTTP), there are no more notion of HTTP specific things such as cookies.
There's one important thing that you should be aware when using WebSockets: it requires a persistent connection to be established between the client and the server. This could make it tricky when you need to load balance your servers. Of course the different implementations of the WebSockets protocol might offer solutions to this problem. For example Socket.IO has a Redis implementation allowing the servers to keep track of connected clients through a cluster of nodes.

Node.js with socket.io

I am looking to build an web application using node.js and possibly socket.io but I am having a lots of confusion regarding whether to use socket.io or go with plain http. In the app the node.js server will be basically an api server which serves json to the javascript client or may be mobile clients too. The web app will also has chat messeneger for its users, this is where socket.io comes in.
I am not sure whether to use socket.io for the whole app or only for the chat part. Although my app itself could benefit from socket.io but its nothing that I think can't be done using plain http and client making more requests to the server.
I have read at several places that sometimes socket.io can be difficult to scale for more users.
Socket.io often crashes and specially creates probs when there are firewall in clients system.
More importantly.....I checked out socket.io user list and did not find many users, so was curious to know what kind of platform is more know chat network like facebook messenger, google talk etc are built upon, Are any built using http-ajax and continues querying to the server.
Please help me out in solving this question. Some might argue that this is a opinion based question. But what actually I am trying to figure out the implementation of socket.io and its limitation.
I would suggest serving your API over HTTP and leave the real-time business to Socket.io. If you are adverse to using Websockets, like #GeoPheonix stated, you can choose from a variety of transport methods using both socket.io and sockjs (https://github.com/sockjs/sockjs-node).
As far as scaling is concerned, I deployed a socket.io based real-time analytics/tracking service for a very large application with ana average of 400+ concurrent connections with no visible performance impact, but this may depend on the implementation and hardware.
Socket.io is faster than plain http. I recommend you to use it for all since you have to have a chat in first place.
In my case, real-time Texas Hold'em-like game can receive up to 2500 concurrent with one node process. However, if you change transport from websocket to xhr-polling, It can receive like more 10x than pure websocket. Your application is just chat so, I guess a little slow down wouldn't be a problem. If you sure you will exceed this number, yes, scale socket.io is a pain.
This problem will happen only if you open socket.io for port other than 80 and 443. If you have frontend web server with other language already, you can still use socket.io on another subdomain to be able to run on port 80 without conflict with your main frontend web server. Socket.io support cross-domain without a problem.
Have you used trello.com? If not, try it :). It's best for task management or even some Agile thing. They used socket.io. https://c9.io/ is another one. It's online IDE with google doc-like collaborative. One thing to note is xhr-polling trasport in socket.io is the same with http-ajax with long-polling (Better than general ajax). You can read more info at:
http://book.mixu.net/node/ch13.html

Socket.io vs AJAX Use cases

Background: I am building a web app using NodeJS + Express. Most of the communication between client and server is REST (GET and POST) calls. I would typically use AJAX XMLHttpRequest like mentioned in https://developers.google.com/appengine/articles/rpc. And I don't seem to understand how to make my RESTful service being used for Socket.io as well.
My questions are
What scenarios should I use Socket.io over AJAX RPC?
Is there a straight forward way to make them work together. At least for Expressjs style REST.
Do I have real benefits of using socket.io(if websockets are used -- TCP layer) on non real time web applications. Like a tinyurl site (where users post queries and server responds and forgets).
Also I was thinking a tricky but nonsense idea. What if I use RESTful for requests from clients and close connection from server side and do socket.emit().
Thanks in advance.
Your primary problem is that WebSockets are not request/response oriented like HTTP is. You mention REST and HTTP interchangeably, keep in mind that REST is a methodology behind designing and modeling your HTTP routes.
Your questions,
1. Socket.io would be a good scenario when you don't require a request/response format. For instance if you were building a multiplayer game in which whoever could click on more buttons won, you would send the server each click from each user, not needing a response back from the server that it registered each click. As long as the WebSocket connection is open, you can assume the message is making it to the server. Another use case is when you need a server to contact a client sporadically. An analytics page would be a good use case for WebSockets as there is no uniform pattern as to when data needs to be at the client, it could happen at anytime.
The WebSocket connection is an HTTP GET request with a special header requesting the server to upgrade it to a WebSocket connection. Distinguishing different events and message on the WebSocket connection is up to your application logic and likely won't match REST style URIs and methods (otherwise you are replication HTTP request/reply in a sense).
No.
Not sure what you mean on the last bit.
I'll just explain more about when you want to use Socket.IO and leave the in-depth explanation to Tj there.
Generally you will choose Socket.IO when performance and/or latency is a major concern and you have a site that involves users polling for data often. AJAX or long-polling is by far easier to implement, however, it can have serious performance problems in high load situations. By high-load, I mean like Facebook. Imagine millions of people loading their feed, and every minute each user is asking the server for new data. That could require some serious hardware and software to make that work well. With Socket.IO, each user could instead connect and just indefinitely wait for new data from the server as it arrives, resulting in far less overall server traffic.
Also, if you have a real-time application, Socket.IO would allow for a much better user experience while maintaining a reasonable server load. A common example is a chat room. You really don't want to have to constantly poll the server for new messages. It would be much better for the server to broadcast new messages as they are received. Although you can do it with long-polling, it can be pretty expensive in terms of server resources.

socket.io websocket fallbacks

I want to use dotcloud with node.js + socket.io for realtime applications.
But they don't support websockets.
Will there be noticeable bandwidth or performance degradation by relying purely on fallbacks?
Is it worth it to use my own server? Linode or aws or whatnot.
Thanks.
I'm implementing an instant messaging system which depends completely on websocket. As the web is evolving quite fast and websocket was in the web standard, I decided to use flash websocket fallback for any browser that don't support it by default (Firefox, Opera). Here is what you may want to know:
I use websocket. I use a pure websocket server. I don't use any other protocols. I don't use socket.io. I must say that if you decide to use only websocket, you won't have benefit from socket.io lib, even the development time. It only adds unnecessary overhead to your server because of multiple transportation layers support.
At client side, I use websocket + flash websocket fallback which implements websocket specs using flash socket and I would say that there's no noticable difference. The only thing you should know that is due to the "same origin policy", you may need to serve flash socket policy request your own (run on port 843 by default) to allow the flash socket to connect in.
We're currently using private server because we have a dedicated sysadmin. However, it's better if you can just focus on doing what you intended to do, and not on unwanted things. Oh, and sometimes, it's better if you have complete control of your own server :-).
Hope it helps.

Resources