phpsocket.io icon indicating copy to clipboard operation
phpsocket.io copied to clipboard

Should the emit callback work?

Open Demo-Nick opened this issue 5 years ago • 1 comments

I'm trying to do something like:

$socket->emit('test', function($data) {
   var_dump($data);
});

And then on client side (v2.3.1):

socket.on('test', (callback) => {
    console.log(callback);
    callback('CALLBACK WORKING');
});

But client shows empty object and nothing happening. P.S. In reverse way it works fine (if emit from client and then trigger callback on server).

Demo-Nick avatar Dec 26 '20 05:12 Demo-Nick

  • When you emit from server, you should emit either a string or a json. In your case, the second parameter of emit is a function.
  • When you setup a listener on client (emit.on, in js), the second argument is a callback, which is a function that receives the data sent from server. What you're doing is trying to call this data as a function, which will not work.

Try this code: server:


$socket->emit('test', 'Message sent from server!);

client:

socket.on('test', (data) => {
    console.log('Message received in client:');
    console.log(data);
});

Alternatively, you could try defining this callback and passing it to the listener, like this:

function callback (data) {
    console.log('Message received in client:');
    console.log(data);
}

socket.on('test', callback);

DanEscudero avatar Feb 03 '21 20:02 DanEscudero