Is it possible to create a custom event emitter and listener (like there's in socket.io) for 'ws' websocket module in NodeJS. If so then, how can I achieve it?
// Here's what I wanna achieve (should work vice-versa):
// listening on server
WebSocket.on('connection', function (ws) {
ws.on('myCustomEvent', function(data) {
// do something with the data
});
});
// emitting from client
socket.emit('myCustomEvent', data);
I'm new, but after a bit of searching the answer appears to be no.
It seems like the accepted way, according to this post, is to use a message format like [eventname, data_object]
and then parse it
This is extremely old but I ran into this problem earlier today.
What I managed to get working was to use the built in addEventListener
property as displayed underneath.
ws.addEventListener('YourCustomEvent', (data) => {
// data.data contains your forwarded data
console.log(data.data)
})
Something to remember is that socketio has a special structure which you have to parse manually while using HTML5 WebSockets.
You are able to do the same with the message
event (and so on)
ws.addEventListener('message', (data) => {
// data.data contains your forwarded data
console.log(data.data)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With