As a web developer, I have developed a chat service and some other real-time collaborative services with the help of third-party services like Redis or Pusher. They provide simple API's that I can use publish/subscribe model to achieve bidirectional communication over the webserver. I want to now implement a simple push notification without the use of any third-party services, but I am not quite sure how to achieve this. The situation is as below:
- Backend is in Python (Django)
- A user receives a private message from another user.
- The recipient should be notified without having to refresh the web browser.
My questions:
- From this post, Django seems a bad option to achieve such functionality while Node.js is a good one. Is it true? If it is, why is that?
- Is it possible to open a websockets from client to the server, to listen to certain changes to a specific model? (ex. when there's a new message in Message model, update the DOM)
I appreciate any help a lot!
WebSockets are exactly what you want here. They are however, a (comparatively) recent addition to browsers and as a result, support is not ubiquitous. WebSocket Support
The websocket model allows you to connect a socket from a server to a client with a web browser, then send messages from the server and receive them asynchronously at the client and vice versa.
Because Node.js is Javascript and the chances are you will be writing your client in Javascript, it lends itself as a sensible choice for writing coupled components, such as in this scenario.
The most popular WebSocket library is Socket.io which was built for use with Node.js. With Socket.io, your notification model would look something like this:
Server
io.sockets.on('connection', function (socket) {
socket.emit('notification', { name: 'Notification', message: 'It\'s here');
});
Client
var notifications = document.getElementById('nlist');
socket.on('notification', function(notification) {
var div;
// make some DOM changes
document.title = notification.name;
div = document.createElement('div');
div.innerHTML = notification.message;
notifications.appendChild(div);
socket.emit('received-notification');
});
Socket.io allows you to use custom event names, as shown here, which makes designing communication APIs that little bit easier. It also has fallbacks for XHR Long Polling and Flash sockets, in the circumstance that the user does not have Web Sockets.
Node will be faster than Django in this circumstance, but you may find that your codebase is more manageable in Django if this is your first venture into Node. It can be kinda difficult to design an application with a series of callbacks like this. I haven't ever used WebSockets with Django, but my experience with Tornado and WebSockets has been poor.