Answer the question
In order to leave comments, you need to log in
How to isolate an event for a specific user?
I use websockets and ws.
In the usual case, ws is a single specific connection, i.e. this code sends a response directly to the sender
wss.on('connection', ws => {
ws.on('message', message => {
const { event, payload } = message;
ws.send(payload);
});
})
const EventEmitter = require('events');
const pubsub = new EventEmitter();
wss.on('connection', ws => {
pubsub.on('test', payload => {
ws.send(payload);
});
ws.on('message', message => {
const { event, payload } = message;
pubsub.emit(event, payload);
});
})
Answer the question
In order to leave comments, you need to log in
const EventEmitter = require('events');
const pubsub = new EventEmitter();
wss.on('connection', ws => {
pubsub.on('test', (payload, _ws) => {
if (_ws !== ws) {
return;
}
ws.send(payload);
});
ws.on('message', message => {
const { event, payload } = message;
pubsub.emit(event, payload, ws);
});
})
const EventEmitter = require('events');
const pubsub = new EventEmitter();
wss.on('connection', ws => {
ws.on('message', message => {
const { event, payload } = message;
pubsub.emit(event, payload, ws);
});
});
pubsub.on('test', (payload, _ws) => {
_ws.send(payload);
});
const EventEmitter = require('events');
const pubsub = new EventEmitter();
wss.on('connection', ws => {
ws.on('message', message => {
const { event, payload } = message;
pubsub.emit(event, { payload, ws });
});
});
pubsub.on('test', ({ payload, ws }) => {
ws.send(payload);
});
const EventEmitter = require('events');
const pubsub = new EventEmitter();
wss.on('connection', ws => {
ws.on('message', message => {
const { event, payload } = message;
pubsub.emit(event, payload, outcome => ws.send(outcome));
});
});
pubsub.on('test', (payload, send) => {
send(payload);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question