I have a similar issue to a previous question (Adding data to a socket.io socket object). I am using socket.io 1.3.4 and would like to add additional data to a socket when it connects. Socket.io used to have a method called set which allowed for this, but it seems to longer work. Is there a new way to do this now?
2 Answers
The correct way to do it as of v4 is to use data property:
this.ioServer.on('connection', async (socket) => {
const user: IUser = socket.handshake.auth.user
socket.data.user = user
...
1 Comment
Daggie Blanqx - Douglas Mwangi
socket.data.user = {fname:'John',lname:'Doe'}; works really great on v4. Thank you.These get/set methods appear to have been removed for 1.0:
http://socket.io/blog/introducing-socket-io-1-0/#scalability
I think the new practice is to simply set properties on the socket object directly as suggested in the question you linked.
You can see an example of this in socket.io's chat example:
https://github.com/Automattic/socket.io/blob/318d62/examples/chat/index.js#L36
3 Comments
user2924127
Sorry I forgot to mention. I want to add these sockets into 'rooms' which will go over a few machines. This method seems to add a global list, but will this global list be able to be accessed by other machines? As well, as the solution posted in the question I posted, would this way of saving socket object data cause naming conflicts?
Andrew Lavers
Oh I see. The option of using get/set to synchronize state across nodes was also removed with 1.0: socket.io/blog/introducing-socket-io-1-0/#scalability If you want to persist some shared state across nodes it should be simple enough to do it directly with redis.
user2924127
Yes I looked at this feature, but I would really like to avoid any additional databases for this feature if I can.
socketobject is a javascript object. You can just add your own custom properties to it.socket.myProp = "foo";.