3

I'm building a search app using Node.js and Express, and I want to add an autocomplete feature. Previously I've used Socket.io to build a chat app so Socket.io came out in my mind first.

But I did some research and it looks like many people are using AJAX for autocomplete, so what are the difference between the two implementations?

I don't really have much experience with TCP and HTTP protocols so I would really appreciate clear and simple answers for noobs :)

yzhan
  • 170
  • 1
  • 3
  • 13

2 Answers2

5

First thing first, your use case is to create an autocomplete feature. What that means? that means when you are inserting a letter in your input field you will request a server with the term you want to find to receive all the autocomplete values.

As a developer when you read this feature details, you should have in mind the word event in our case the keypress event. So each time this event is triggered you want to request the server to get the autocomplete list. What possibilities do you have to do that ?

First most commonly used for this type of scenarios is a simple ajax call, which will send an request and when finished will update the autocomplete with the corresponding details. As we see in this case for each letter typed, a request potentially can be made (usually you can implement a debounce function) to reduce the numbers of calls. The good think here is that you will close the connection once you received your details, and there are million of plugins with jquery which are doing that just fine.

Second approach is to use socket.io which also is a viable option, you will open your connection once, and for each keypress event you will emit your get details which will be usually faster cause you will reuse the existing connection. The con part here is that you will need to create it by yourself I do not know any plugins which are implementing autocomplete with socket.io.

Conclusion

Socket.io

  • faster due to reuse of existing connection
  • more labor work, very little plugins|extensions
  • good for the case when you already using socket.io on your app
  • overkill just for the autocomplete feature

Ajax

  • slower in comparison with socket.io
  • tons of plugins
  • overall be a good solution for this use case.
Alexandru Olaru
  • 6,842
  • 6
  • 27
  • 53
4

Socket.io/Websockets are primarily for real-time interactions between the server and the client(s). Socket.io also require a constant connection and more setup to have the server respond to a single client. Either way the speed will primarily be dependent on server processing. In the case of a search autocomplete, where you're literally sending a request to the server and expecting a single response back to the requesting client, I'd personally go with the AJAX route. This question has a few good answers that go into detail about this a bit more: What is the disadvantage of using websocket/socket.io where ajax will do?

Quangdao Nguyen
  • 1,343
  • 11
  • 25