12

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.

joshua-anderson
  • 4,388
  • 5
  • 32
  • 54

1 Answers1

25

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
Peter Lyons
  • 137,901
  • 29
  • 269
  • 269
  • Thanks for the quick reply. So unless you have a good reason to do otherwise use web sockets for active communication. Do web sockets have any disadvantages? – joshua-anderson Jun 24 '13 at 00:39
  • Browser support for web sockets is not yet as complete as it is for ajax, especially on mobile. Like all new technologies, the tools and community knowledge around them is not as mature as it is for ajax. Also there can be deployment challenges with proxies and web servers requiring specific configuration before web sockets will work. – Peter Lyons Jun 24 '13 at 00:43
  • @PeterLyons So if i am making a notification system then web sockets are best, right? – Utkarsh Dixit Mar 22 '15 at 06:18
  • 2
    But why use socket.io instead of simple node.js webSockets? What's the use case / advantage? – Agent Zebra Jan 04 '16 at 04:15
  • 1
    @AgentZebra My guess is that you should elect to use socket.io when you control only one side of the conversation as socket.io will downgrade as necessary when Websockets is not available on the other side. If you control both sides it seems to me there is no downside to using node.js Websockets. But I'm open to correction and education here. – Ric Jul 18 '16 at 20:57