简体   繁体   中英

Emit event for particular user if login functionality in application in Socket.io with Node.js

I have used methods socket.on and io.emit , And i got response to all users. But, i want to get response for particular user.

But my application contains login functionality and i followed this post on stackoverflow, and they are saying we need unique userId and socketId in an object for a particular user to emit an event for a particular user. But i am getting the userId after login , But we want it when user connect to app.

So can anyone please help me with the same?

  1. In your node.js, create a global array 'aryUser', each element contains the socketid and loginid.

  2. node.js onConnect (new connection), add a new element to the array with the socketid and set loginid = empty.

  3. after the user login, emit an event from client to the server, eg:

socket.emit('userloginok', loginid)

  1. in node.js, define a function:

socket.on('userloginok', loginid)

and in this function, search the aryUser with the socketid and replace the empty loginid inside the array element with the parm loginid.

  1. in node.js, define the function:

socket.on('disconnect')

and in this function, search the aryUser, use aryUser.splice(i,1) to remove the user just disconnected.

that means, aryUser contains all users connected, some of them logined, some of them not logined. And you can use the socketid of the array to send message to particular user, and/or all users.

Example Source Code:

  1. server.js

http://www.zephan.top/server.js

  1. server.html

http://www.zephan.top/server.html.txt

rename server.html.txt to server.html, put server.html and server.js in the same directory, and run:

node server.js

Yes, you definitely need socketId in order to send and receive messages between two specific users.

UserId is required just to keep track of socketId associated with the particular user or you can manage it with some other way as well that's up to you.

As per your question, you have userId of the user and you need socketId of that user! So, in this case, you can pass userId when that particular connects to a socket server from the client side as shown in below snippet,

const socket = io(this.SOCKET_SERVER_BASE_URL, { query: `userId=${userId}` });

And you can read this user on nodejs server like this,

const userId= socket.request._query['userId'],
const socketId= socket.id

Now store this socketId in somewhere, for example, Redis or some sort of caching mechanism again up to you, just make sure fetching and retrieval should be fast.

Now while sending a message just pull the socketId from your cache and emit the message on that socketId by using below code,

io.to(socket.id).emit(`message-response`, {
    message: 'hello'
 });

I have written a complete blog post on this topic on both Angular and AngularJs , you can refer those as well.

Edit 1:

Part 1 => When your user completes the login request, then make the connection to the socket server. Assuming you are using React Or Angular After a successful login you will redirect your user to home component(page). On the Home component(page) make the socket server connect by passing the userId just like this,

const socket = io(SOCKET_SERVER_BASE_URL, { query: `userId=${userId}` });

PS you can get userID from URL or maybe using a cookie that is up to you.

Once you receive this socket connection request on the server, then you can read the userID query and you can get socketId associated with it and store it in cache like this,

io.use( async (socket, next) => {
    try {
        await addSocketIdInCache({
            userId: socket.request._query['userId'],
            socketId: socket.id
        });
        next();
    } catch (error) {
        // Error
        console.error(error);
    }
});

Part 2 => Now, let's say you have a list of the users on the client side, and you want to send a message to particular users.

socket.emit(`message`, {
    message: 'hello',
    userId: userId
 });

On the server side, fetch the socketId from the cache using UserId . Once you get the socketId from cache send a specific message like this,

io.to(socketId).emit(`message-response`, {
    message: 'hello'
 });

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM