Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 967
joshua-anderson Avatar asked Jun 24 '13 00:06

joshua-anderson


1 Answers

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
like image 161
Peter Lyons Avatar answered Sep 29 '22 03:09

Peter Lyons