Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating socket.io into REST API

so i'm building an iOS app and i've started building a REST API w/ nodejs, express, & mongodb. I'm currently adding instant messaging and notifications to my app so i've been reading up on websockets(socket.io). After tons of reading, I honestly cannot wrap my head around the concept and how to integrate into my API.

For example, I have this API route:

// create new message
app.post('/newmessage', function (req, res, next) {

  if (!req.body.message ) {
    res.json({success: false, msg: 'You must type a message.'});
    console.log('message: ' + req.body.message);

  } else {

     var newMessage = new Message({
     fromUser: ObjectID(req.params.id),
     toUser: ObjectID(req.params.id),
     message: String,

     }); 

     // save new message
      newMessage.save(function(err) {
      if (err) {
       res.json({success: false, msg: 'message was unsuccessful.'});
      } else {
       res.json({success: true, msg: 'message sent!'});
       console.log(newMessage.createdAt);
       console.log(newMessage.updatedAt);

      }

    });

  }

});

How would I integrate socket.io into this specific call? Would I create a Socket.js file and export from there? Backend isn't my thing at all, so I apologize if this is a poor question. Thanks!

like image 549
V1P3R Avatar asked Sep 11 '26 12:09

V1P3R


1 Answers

The general architecture for using a webSocket or socket.io connection for instant messaging or server-push notifications is as follows:

  1. Each client makes a webSocket or socket.io connection to the server.
  2. The server is listening for those incoming connections and uses some sort of cookie on the initial connection to identify which user is connecting.
  3. The server then holds those connections open for the duration of the user session and listens for incoming messages on them.
  4. At any time, if the server wishes to send a notification to the client, it can find the connection belonging to the desired client and send a message on that connection.
  5. The client will be listening for incoming messages and will receive that message and can then process it.
  6. For instant messaging, a client would send a message to the server that essentially says "send this message to Bob" (where Bob is some user ID for some other user on the system). The server would receive that message from the other client and would then find Bob's connection and send the message to Bob on that connection.

I would recommend using socket.io as it offers a number of useful features on top of webSockets and there should be socket.io libraries for all platforms you would be using. The socket.io documentation includes a demo app that does chat which will give you some idea how things work with socket.io.

like image 199
jfriend00 Avatar answered Sep 13 '26 02:09

jfriend00