BigSmoke
BigSmoke

Reputation: 35

Return a value from socket.io to client side

I am trying to receive the ID of the current drawer from the server to the client for something I'm making. this is what i've got so far

client:

    socket.emit('returnDrawer');

    socket.on('returnDrawer', function(ret)
    {
        console.log("id:", ret);
    })

server:

socket.on('returnDrawer', function() {
    return users[currentDrawer].ioid;
});

but my client side callback is not being called at all with the current drawer id, could use some help.

Upvotes: 1

Views: 12621

Answers (3)

meg768
meg768

Reputation: 101

You may send a callback function as a parameter to emit(). Here is an example from a project of mine. No drawers but animations.

Client side

socket.emit('animate', 'text', payload, (response) => {
    console.log(response);
});

Server side

socket.on('animate', (animation, payload, callback) => {

    callback = typeof callback == "function" ? callback : () => {};

    try {
        this.runAnimation(animation, payload);
        callback({status:'OK'});
    }
    catch(error) {
        callback({error:error.message});
    }

});

Upvotes: 9

Supermacy
Supermacy

Reputation: 1489

You can use different event names for sending and receiving. This will help you to scale well in future.

For example, above code can be written in:-

// implementing client side
  socket.emit('returnDrawer');
  socket.on('returnDrawerResponse', function(message) {
    console.log('id', message)
  });

For server side you can write this like:

// implementing server side
  socket.on('returnDrawer', function(){ 
   // write Your awesome code here
   const userId = users[currentDrawer].ioid()
   socket.emit('returnDrawerResponse', userId)
 })

Upvotes: 6

dun32
dun32

Reputation: 696

Have you tried something like :

client

socket.emit('giveMeDrawer');

socket.on('returnDrawer', function(ret) {
  console.log("id:", ret);
})

server

socket.on('giveMeDrawer', function() {
  socket.emit('returnDrawer', users[currentDrawer].ioid);
});

Or follow this guide (from socket.io documentation).

Upvotes: 1

Related Questions