elephant.io
elephant.io copied to clipboard
Socket.io and arguments not working
My setup:
- PHP 7.1
- socket.io 2.2.1 (latest) server
Take the following sample code:
server.js snippet
io.on('connection', (socket) => {
socket.on('test', (data) => {
console.log(data);
});
});
client.php snippet
$client = new Client(new Version2X($url));
$client->initialize();
$client->emit('test', [2]);
Given this example the variable data
in the nodejs socket.io server equals [ 2 ]
, an array with a single element, 2
. However what i expected would be that data
equals 2
.
Multiple arguments are handled as multiple parameters, so it would look like this:
socket.on('test', (param1, param2, param3) => {
console.log(param1);
});
Thus (at least for me) this lib wont work with the socket.io server correctly.
To fix this i found it is enough to change
\json_encode([$event, $args])
to
\json_encode(array_merge([$event], $args))
in the Version1X.php
engine.
Is this interfering or breaking anything, or could it be fixed via a PR like that?
That would be feasible, yes, but there would be a break. Instead of always getting an array, we would get something else.
Even better, it would be to up the php constraint (it's way past the time we did it...) and use the splat operator : \json_encode([$event, ...$args])
.
To push things further, we could also use that operator in the signature (function emit($event, ...$args)
, so we can call emit('test', 2, 3, 'foo', ['bar' => 'baz'])
), but that would really be a bc break. :}
How do you suggest to implement this breaking change? I'm not sure since which socket.io version the params were not passed as array anymore. Just stumbled across this as i looked into connecting to a third party socket.io server.