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

Is it possible to create a custom emitter and event listener (for example, in socket.io) for the ws' sssocket module in NodeJS. If so, how can I achieve this?

// Here I want to achieve (should work the other way around):

// 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);
+7
source share
2 answers

This is a very old problem, but today I ran into this problem. I managed to use the built-in property addEventListeneras shown below.

ws.addEventListener('YourCustomEvent', (data) => {
    // data.data contains your forwarded data
    console.log(data.data)
})

Keep in mind that socketio has a special structure that needs to be analyzed manually when using HTML5 WebSockets.

message ( ..)

ws.addEventListener('message', (data) => {
    // data.data contains your forwarded data
    console.log(data.data)
})
+2

, , , .

, , this, , [eventname, data_object],

0

Source: https://habr.com/ru/post/1668532/


All Articles