Does the WebSocket module support using emit? I can only make send work.
We're using custom message types to do things like authentication, something like:
const socket =io.connect(host);
socket.on('connect', function() {
socket.emit('authenticate', {token}, () => {
// Ack. callback
});
});
socket.on('my-custom-message-type', onCustomMessage);
}
(ping @gbts )
Hi @caalle , the websocket module supports the vanilla websocket protocol. So our version of socket.send is similar to node.js's ws send, i.e. it sends raw data frames to the server. Socket.io is an additional abstraction over that protocol and one of the things it does is to add a type to each message.
Looking up their client's source code, what socket.io's emit seems to do is to pack the message type & data in a JSON array and then send it, which I assume you could emulate with something like this:
socket.send(JSON.stringify(['authenticate', {token}]))
and conversely, to receive custom messages you could parse the array and check the event type:
socket.on('message', function(raw) {
var args = JSON.parse(raw);
if (args[0] == 'my-custom-message-type') {
var data = args[1];
...
}
});
Now the reason that our send worked for you without encoding the data is that socket.io probably defaults to the 'message' event when it receives unpacked data. Take the code above with a grain of salt as I'm not very familiar with socket.io, so maybe I'm missing some additional step here.
The ws docs has been recently updated here
Closing this issue.
Most helpful comment
Hi @caalle , the websocket module supports the vanilla websocket protocol. So our version of
socket.sendis similar to node.js'swssend, i.e. it sends raw data frames to the server. Socket.io is an additional abstraction over that protocol and one of the things it does is to add a type to each message.Looking up their client's source code, what socket.io's
emitseems to do is to pack the message type & data in a JSON array and then send it, which I assume you could emulate with something like this:and conversely, to receive custom messages you could parse the array and check the event type:
Now the reason that our
sendworked for you without encoding the data is that socket.io probably defaults to the 'message' event when it receives unpacked data. Take the code above with a grain of salt as I'm not very familiar with socket.io, so maybe I'm missing some additional step here.