Monday, 1 May 2017

How do I properly create a chat room for 2 users using socket.io?

I know that there are many answers out there, but in my use case, it is a bit confusing. I just want to see whether my solution is good enough

My use case is very simple when user A buys something from user B, a chat room for both users will be created.enter image description here

Technically to go to that room, buyer or seller must use the API which is

app.get('/room/:roomid', (req, res, next) => {
   // Find the appropriate room using mongoose/mongodb to show relevant data to this HTML page
   Room.findOne({_id: req.params.roomid }, function(err, room) {
      // Show some data on the HTML page using Handlebars or EJS
   });
});

This is simply to handle the room page for both buyer and seller.

My confusion is at making both user join the room. On the API, should I run socket.join? for example

app.get('/room/:roomid', (req, res, next) => {
      // Whenever someone comes to this room, do 
      socket.join(req.params.roomid); // Will this work?
       Room.findOne({_id: req.params.roomid }, function(err, room) {

       });
    });

Let say it is possible, to use socket.join on API level (Probably need to use redis or something because it is outside of socket.io environment)

Should I send the roomid using session to socket.io environment?

Updated version of the API

app.get('/room/:roomid', (req, res, next) => {
          const roomid = req.params.roomid;
          socket.join(roomid);
          req.session.roomid = roomid;
           Room.findOne({_id: req.params.roomid }, function(err, room) {

           });
        });

On the socket.io environment

io.on('connection', function(socket) {
    // This will trigger, when user submit on the input box
    socket.on('chatTo', (data) => {
      // Sending to the appropriate room. 
      io.to(socket.request.session.roomid).emit('incomingChat', {
         data
       });
    });

});

My goal is simple, buyer buys something from seller, chat room is created and whenever buyer or seller hits the chat room api, either one of them will join the room, thus can send message to each other, because the roomid is unique.

Is my solution efficient enough or there is a better way to handle this problem properly?



via sinusGob

No comments:

Post a Comment