0
votes

I'm developing an online, text-based RPG (Github); currently I've a PHP backend that stores session data in a redis server. For everything where real-time comunication is needed (chat, messaging and the list of connected users) I use Node.js and socket.io for websockets.

I have currently 3 namespaces on my websocket server:

  1. Messaging Server
  2. Online Server
  3. Chat Server

I've made it work, but I'm afraid that most of it is made off of "hacking". Right now I've problems to send a message to a specific client. For example, if I'm writing a private message to another user, when I click "send" I want the following logic.

  1. User is writing his message, when he clicks on "send" the client emits to the websocket server something like {"sender": 15, "message": "blablabla", "receiver": 17};
  2. On the websocket server, the server gets the event and from there I must align the "receiver" with the client session. At every connection to a namespace I add to the socket object two properties, accountId and accountName that are results of my Auth module.

    /* POSTA SERVER */ postaServer.on('connection', function postaConnect(socket) { var phpSessId = cookie.parse(socket.request.headers.cookie) .PHPSESSID; if (phpSessId === undefined || phpSessId === '') { console.log('Sessione non trovata'); socket.disconnect(); } else { // modulo socket_auth checkSession(phpSessId, function (auth) { if (auth) { // Auth retrieves account id and account name from redis socket.accountId = auth.id; socket.accountName = auth.nome; socket.emit('serverMessage', 'connesso al server di posta'); var conn = mysql.createConnection(DB); getMessaggiPosta(socket.accountId, conn, function (err, result) { if (err) { console.log(err); } else { socket.emit('refreshPosta', result); } }); } else { socket.disconnect(); } }); } });

How can I emit an event only to a specific client without the use of the built-in socket.id?

1

1 Answers

0
votes

You could try the module "socket-io-emitter" for node.

var io = require('socket.io-emitter')({
  host: redisHost,
  port: redisPort
});

And then emit to a certain user via a user specific key:

io.to('myKey' + '_user_' + userId).emit('myEvent', {
  data: 'hello'
});