BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11673

sockets instead of ajax for client/server communication

In this node.js forum app https://github.com/designcreateplay/NodeBB, which allows you to follow other users on the site, I noticed that it seems to use sockets to communicate information I would have been expected to be communicated via an ajax post request. For example, when you click the button to follow another user (which this forum software allows), the socket on the client emits an 'api:user.follow' event, which is then listened for on the server, as you can see below.

Can you explain why someone would or wouldn't want to use sockets instead of ajax for this type of functionality? I assume there's pros and cons to each, but I don't know them.

client

followBtn.on('click', function() {
                socket.emit('api:user.follow', {
                    uid: theirid
                }, function(success) {
                    if (success) {
                        followBtn.addClass('hide');
                        unfollowBtn.removeClass('hide');
                        app.alertSuccess('You are now following ' + username + '!');
                    } else {
                        app.alertError('There was an error following' + username + '!');
                    }
                });
                return false;
            });

Server

   socket.on('api:user.follow', function(data, callback) {

            if (uid) {
                user.follow(uid, data.uid, callback);
            }
        });

Upvotes: 2

Views: 146

Answers (1)

Paul Mougel
Paul Mougel

Reputation: 17048

NodeBB doesn't use sockets: it uses Socket.io, which is a library that enables you to use "real-time" communication between browsers and the server.

You can easily find AJAX vs. Socket.io comparisons on the internet, but here are some differences:

  • Socket.io uses one persistent connection between the client and the server; whereas each AJAX request uses a new connection, which means sending the lengthy HTTP headers, cookies, etc.
  • Socket.io messages can't be cached, AJAX requests can be
  • Socket.io provides namespaces, volatile messages, broadcasts...

In the particular case of a forum, the main advantage of using Socket.io is to provide real-time functionalities such as instantly displaying new messages on a thread, which are automatically pushed from the server to the client. If some messages could be sent using AJAX (such as following a user), I suppose the developers don't want to introduce the mental overhead of using two different technologies to communicate between the client and the server, as Socket.io can also handle those messages just fine.

Edit: As pointed in the comments, Socket.io selects a transport protocol, depending on the browser. Websocket is preferred, but it can switch to AJAX long polling or an iframe if needed.

Upvotes: 2

Related Questions