Saturday 18 August 2018

Sending Message to Particular User with Socket.IO

I am trying to use socket.io to create a chat app, where a user can send a message to another specific user. However, I am having trouble doing so. Here's the code:var express = require("express"), app = express(), server = require('http').Server(app), io = require('socket.io')(server), middleware = require("./middleware"), //Middleware to check whether user has logged in msg = io.of('/messages'); //List of connected users var onlineUsers = [] msg.on('connection', function (socket){ //Push new connected user to the onlineUsers array onlineUsers.push({id: req.user._id, socketID: socket.id}) socket.on('message', function(msg){ io.to(`${socketId}`).emit('message', msg); //Message to specific user }); }); //Check whether user has logged in msg.use((socket, next) => { if (middleware.isLoggedIn) return next(); next(new Error('Authentication error')); }); server.listen(process.env.PORT); There are two issues I am currently facing:I am not sure how to obtain the "req.user._id" of each new connected user. I have no problem doing so in the Express.js callback when requesting a route. But I have problem here since it doesn't have the usual Express.js callback pattern. The reason for doing so is to associate each user's id (req.user._id), which is unique in MongoDB, with their respective socket.id.I am not sure how to know what user the client wants to send messages to. I am trying to build a chat app similar to Facebook messenger, where the left panel shows the friends of the user. When the user click on one of the friends to chat with him/her, how do I know which friends the user wants to message to? I am thinking that when the user sends a message, the message is send along with the friend's id. Then the server could find the socket.id associated with the friend's id in the onlineUsers array, and then send the message to the socket.id.

Submitted August 19, 2018 at 07:17AM by VickNicks

No comments:

Post a Comment