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!
The general architecture for using a webSocket or socket.io connection for instant messaging or server-push notifications is as follows:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With