I'm making a chat app with socket.io, and I'd like to use my custom client id, instead of the default ones (8411473621394412707
, 1120516437992682114
). Is there any ways of sending the custom identifier when connecting or just using something to track a custom name for each ID? Thanks!
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
I would use an object as a hash lookup - this will save you looping through an array
Do not change the socket IDs to ones of your own choosing, it breaks the Socket.io room system entirely. It will fail silently and you'll have no clue why your clients aren't receiving the messages.
If you are trying to use a custom id to in order to communicate with a specific client then you can do this
Can store customId (example userId) in object format instead of for loop, this will improve performance during connection, disconnect and retrieving socketId for emitting
`
To set custom socket id, generateId function must be overwritten. Both of
eio
andengine
props ofSocket.io
server object can be used for to manage this operation.A simple example:
It seems to be it has been handled.
It must be in mind that socket id must be unpredictable and unique value with considering security and the app operations!
Extra: If
socket.id
is returned asundefined
because of your intense processes on yourgenerateId
method,async/await
combination can be used to overcome this issue onnode.js
version 7.6.0 and later.handshake
method ofnode_modules/engine.io/lib/server.js
file should be changed as following:current:
new:
Note: At Engine.io v4.0,
generateId
method would accept a callback. So it would not needed to changehandshake
method. OnlygenerateId
method replacement is going to be enough. For instance:or you can override the socket id, like this:
you can see under the array:
io.sockets.sockets