简体   繁体   English

如果使用Node.js在Socket.io中的应用程序中具有登录功能,则为特定用户发出事件

[英]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. 我已经使用方法socket.onio.emit ,我得到了所有用户的回应。 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. 但是我的应用程序包含登录功能,我在stackoverflow上关注了这篇文章,他们说我们需要特定对象中的对象中唯一的userIdsocketId才能为特定用户发出事件。 But i am getting the userId after login , But we want it when user connect to app. 但是我在登录后得到了userId ,但是当用户连接到应用程序时我们想要它。

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. 在您的node.js中,创建一个全局数组'aryUser',每个元素都包含socketid和loginid。

  2. node.js onConnect (new connection), add a new element to the array with the socketid and set loginid = empty. node.js onConnect(新连接),使用socketid将新元素添加到数组,并设置loginid = empty。

  3. after the user login, emit an event from client to the server, eg: 用户登录后,从客户端向服务器发出事件,例如:

socket.emit('userloginok', loginid) socket.emit('userloginok',loginid)

  1. in node.js, define a function: 在node.js中,定义一个函数:

socket.on('userloginok', loginid) 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. 然后在此函数中,用socketid搜索aryUser,并将数组元素中的空loginid替换为parm loginid。

  1. in node.js, define the function: 在node.js中,定义函数:

socket.on('disconnect') socket.on( '断开')

and in this function, search the aryUser, use aryUser.splice(i,1) to remove the user just disconnected. 在此函数中,搜索aryUser,使用aryUser.splice(i,1)删除刚刚断开连接的用户。

that means, aryUser contains all users connected, some of them logined, some of them not logined. 这意味着aryUser包含所有已连接的用户,其中一些已登录,其中一些未登录。 And you can use the socketid of the array to send message to particular user, and/or all users. 您可以使用数组的套接字ID向特定用户和/或所有用户发送消息。

Example Source Code: 示例源代码:

  1. server.js server.js

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

  1. server.html server.html

http://www.zephan.top/server.html.txt 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: 将server.html.txt重命名为server.html,将server.html和server.js放在同一目录中,然后运行:

node server.js 节点server.js

Yes, you definitely need socketId in order to send and receive messages between two specific users. 是的,您肯定需要socketId才能在两个特定用户之间发送和接收消息。

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. 仅需要UserId即可跟踪与特定用户相关联的socketId ,或者您也可以通过其他方式来管理它。

As per your question, you have userId of the user and you need socketId of that user! 根据您的问题,您具有该用户的userId ,并且需要该用户的socketId 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, 因此,在这种情况下,您可以在该特定对象从客户端连接到套接字服务器时传递userId ,如下面的代码段所示,

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

And you can read this user on nodejs server like this, 您可以像这样在nodejs服务器上读取该用户,

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. 现在,将此socketId存储在某个地方,例如Redis或由您决定的某种缓存机制,只需确保获取和检索应该很快。

Now while sending a message just pull the socketId from your cache and emit the message on that socketId by using below code, 现在,在发送消息时, socketId使用以下代码从您的缓存中提取socketId并在该socketId上发出消息,

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. 我已经在AngularAngularJs上撰写了有关此主题的完整博客文章,您也可以参考它们。

Edit 1: 编辑1:

Part 1 => When your user completes the login request, then make the connection to the socket server. 第1部分=>当您的用户完成登录请求时,然后建立与套接字服务器的连接。 Assuming you are using React Or Angular After a successful login you will redirect your user to home component(page). 假设您正在使用React或Angular成功登录后,您将把用户重定向到home组件(页面)。 On the Home component(page) make the socket server connect by passing the userId just like this, 在Home组件(页面)上,通过像这样传递userId使套接字服务器连接,

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. PS,您可以从URL获得用户ID,也可以使用取决于您的Cookie。

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, 在服务器上收到此套接字连接请求后,即可读取userID查询,并获取与之关联的socketId并将其存储在缓存中,如下所示:

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. 第2部分=>现在,假设您有一个客户端用户列表,并且想向特定用户发送消息。

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

On the server side, fetch the socketId from the cache using UserId . 在服务器端,使用UserId从缓存中获取socketId Once you get the socketId from cache send a specific message like this, 从缓存中获取socketId后,请发送类似的特定消息,

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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