Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

When to use socket.io and when to use ajax

When to use socket.io and when to use ajax

Problem

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.

Problem courtesy of: joshua-anderson

Solution

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
Solution courtesy of: Peter Lyons

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

When to use socket.io and when to use ajax

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×