简体   繁体   中英

Check stored client data in particular room in Socket.IO

Is there any way to check client data stored in a socket in a particular room?

Let's say there are "room1" and "room2". Then I want to check whether a socket with name "Guest" exists in "room2".
How can I do something like that?

There may be a way to do that with the Socket.IO internals, but I suggest you use a database (Redis, Mongo) to store the information about your connected clients.

Each time a client logs in, you can check his cookie (session), thus authenticating him. After the client is authenticated and connected, store him in the db (Redis for example) and on disconnect delete him from the db.

Socket.IO doesn't provide that method for you, but it can easily be implemented. I have created a small patch for this before:

https://github.com/3rd-Eden/Socket.IO-node/blob/features/room/lib/socket.js#L60-80

which allows you to get a list of rooms by calling

socket.rooms // returns array

So this requires some socket.io internals hacking but you can easily add that method to socket as socket.io exposes the Socket prototype for you when you do require('scocket.io')

So having that said you probably implement this your self by doing:

require('socket.io').Socket.__defineGetter__('rooms', .. etc ..)

Hope this helps :)

This will give you a hash of all the sockets (in "" ) and sockets in individual rooms:

util.inspect(socketListener.sockets.manager.rooms)

Output looks like:

{"":["LAzOCu5lRdOlbOv7YH8S","597eJrAUmc56EyEKYH8T","uVy_AK8WVJ8oGzE9YH8U","LzZGITUmT9Uf9G-1YH8V","kKgexBImhkwi-FxIYH8W","8NfZC_Lbqv6TctUaYH8X","viSdBTXOVIPR2u8OYH8Y"], "/xyz":["597eJrAUmc56EyEKYH8T","uVy_AK8WVJ8oGzE9YH8U","kKgexBImhkwi-FxIYH8W","8NfZC_Lbqv6TctUaYH8X"], "/abc":["viSdBTXOVIPR2u8OYH8Y"]}

Note that there is a list of all sockets connected and a list of rooms with the sockets that are in that room.

alessioalex's answer is what I would suggest, but here is the direct answer to your question:

In your server's js, create an empty object for guest names (eg var usernames = {}; ) and on join, add a username to whatever your room is

usernames.room1 = [];
usernames.room1.push('you');

or

usernames.room1 = [];
usernames.room1['you'] = 'you';

Latter is easier to deal with sometimes.

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