Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom events for 'ws' Web-Socket module?

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);
like image 311
JantoKarma Avatar asked Feb 01 '17 15:02

JantoKarma


2 Answers

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

like image 76
Alter Avatar answered Sep 18 '22 05:09

Alter


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)
})
like image 37
Yazaar Avatar answered Sep 22 '22 05:09

Yazaar