This website uses cookies to enhance the user experience

Real-time Features with WebSockets

Share:

In web application development, real-time features are becoming increasingly important for providing a dynamic user experience. Sails.js, a MVC framework for Node.js, provides an easy way to build custom, enterprise-grade Node.js applications with built-in support for WebSockets, which is a protocol providing full-duplex communication channels over a single TCP connection. This chapter will delve into the real-time features of Sails.js focusing on how WebSocket is employed for real-time communication.

WebSockets in Sails.js are facilitated by a feature known as sails.sockets. Simplistically, Sails.js gives you a real-time WebSocket server for free!

Let's assume we're creating a movie review app called "CinemaView". In CinemaView, we want to allow users to post their reviews and reactions in real-time.

To begin, we start with a basic setup of a Sails.js application. We won't go over the setup process in detail because it is straightforward and well-covered in the Sails.js documentation.

Let's consider a scenario where we want to notify our users when a new review for a particular movie they've seen is posted. We can achieve this by using WebSocket to broadcast the message to all the clients who are currently watching that movie.

Here's a block of code that shows how you can broadcast real-time messages in Sails.js:

sails.sockets.broadcast('room', 'new review', {review: review});

In this case, 'room' is a dynamic variable associated with a certain movie, ‘new review’ is the event being broadcasted, and {review: review} is the data being sent with the event.

To join a room, you can use the .join method as follows:

sails.sockets.join(req, 'room');

In the example above, req is the request object from the client that wants to join the room named 'room'. Each room can be considered as a separate channel for a particular movie.

When a user navigates to the page of a particular movie, they join a room dedicated to that movie, allowing them to receive and send real-time updates about it. The process of joining a room in our CinemaView application might look something like this:

show: function(req, res) {
  let movieId = req.params.id;

  Movie.findOne({id: movieId}, function(err, movie) {
    if(err) return res.serverError(err);
    if(!movie) return res.notFound(`Could not find movie, sorry.`);

    sails.sockets.join(req, `movie_${movieId}`);

    return res.json(movie);
  });
}

In this case, when a user navigates to a movie's page using a URL like '/movie/321', they are subscribing to the 'movie_321' room.

To broadcast a message to that movie's room when a new review is created, you can do as follows:

createReview: function(req, res) {
  let movieId = req.params.movieId;
  let reviewData = req.body;

  Review.create(reviewData, function(err, review) {
    if(err) return res.serverError(err);

    sails.sockets.broadcast(`movie_${movieId}`, 'new_review', { review: review });

    return res.json(review);
  });
}

Here, whenever a new review is created, all the users currently in the room for that specific movie receive the 'new_review' event and the data of the new review.

It's important to note that Sails.js built-in pub-sub methods like .publishCreate(), .publishUpdate(), and .publishDestroy() automatically use the WebSocket protocol if it's enabled. So anytime you create, update, or delete a model, Sails.js will automatically send out a message to any client subscribed to that instance of the model.

For example, if you were to create a new Review:

Review.create(req.body).exec((err, review) => {
  if (err) { return res.serverError(err); }

  Review.publishCreate({id: review.id, movieId: review.movieId});

  return res.ok();
});

When the server runs Review.publishCreate(), Sails.js will send a message to any client subscribed to the 'review' model instance in the database. The client-side code receiving the message might look something like:

io.socket.on('review', (msg) => {
  switch (msg.verb) {
    case 'created':
      console.log(`A new review was added to movie id ${msg.data.movieId}`);
      break;
    default:
      console.log('An unknown message was received from server.');
  }
});

In conclusion, Sails.js with WebSockets allows us to easily develop applications with real-time functionalities. By simply broadcasting messages, applying different rooms for different movies or users, and using Sails's built-in pub-sub methods, we can create upgrade our CinemaView application with dynamic features for a more enhanced user experience.

0 Comment


Sign up or Log in to leave a comment


Recent job openings