Home > Enterprise >  Accessing The Data Object of Socket.IO-Server From The Socket.IO-Client
Accessing The Data Object of Socket.IO-Server From The Socket.IO-Client

Time:12-06

In socket.io server a property can be added to the socket.data object. How do i access such a property at the client side (socket.io-client)?.

// Server code

io.on('connection', socket => {
   socket.data.customId = getCustomId();
   io.emit('connected', {success: 'true'})
})

// Client code

socket = io('http://localhost:5000');

socket.on('connected', data => {
  console.log('SOCKET_DATA:', socket)
  console.log('SOCKET_CUSTOM-ID:', socket.data.customId); // produces 'undefined'
})

I would like to access the customId i added at the server from the client side. The data attribute don't even exist on the socket object displayed at the console at the client side.

Any help would be appreciated

CodePudding user response:

If you wanted some way to have access to that, you would have to create some request that sends to the server. Only the server stores that information. You could do something like the following on client side:

socket.emit("getCustomId", (id) => {
   console.log("SOCKET_CUSTOM-ID:", id);
});

Then the server can listen and respond with the custom id:

socket.on("getCustomId", (callback) => {
    callback(socket.data.customId);
});

That callback parameter on the server side connects back to the unnamed ES-6 function declared in the socket.emit("getCustomId"); call, which you can see here on this SO question about socket.io callbacks

  • Related