David Li
David Li

Reputation: 1290

Using AJAX vs. socket.io socket messages

I am writing a chat application with friend request capabilities, and currently using socket.io events to send/receive messages between users.

I'm conflicted on when to use AJAX and when to use sockets in the event that I have access to the socket. i.e.

$.ajax({url:'friendAdd'}) vs socket.emit('friendAdd');

for all my friend request logic.

Would it be better to stay consistent throughout the application and use sockets for all other requests, or are there reasons that using AJAX would be more optimal?

Upvotes: 0

Views: 482

Answers (1)

jfriend00
jfriend00

Reputation: 708026

I'd say it really depends on a request by request basis what you're doing. Once you have a socket.io connection established, it is technically a bit more efficient to just use it for everything since the connection is already established on both ends so all you have to do is send a message packet.

But, some requests from client to server (depending upon what they are) may benefit from some of the HTTP infrastructure that is already built into your HTTP framework on the server (like Express). For example, if you were uploading a file, you could do it over the socket.io connection, but there's a lot of code already built to do that over HTTP that you could just use and that may not already exist for doing that type of request over socket.io. Or, if you are using various Express middleware for sessions, cookies, authentication, routing, etc... it may be much easier to take advantage of all that existing infrastructure and modules in the http world rather than try to reimplement for socket.io messages.

Personally, I would tend to keep the socket.io traffic to chat related traffic only and obviously anything that must be server push and then use regular Ajax calls for other functions that aren't directly chat. But, there's no exact answer there, it really depends upon what you think is the cleanest architecture and best encapsulation of functionality.

FYI, some interesting discussion (and other references) around this topic in this other answer: Ajax vs Socket.io

Upvotes: 2

Related Questions