0

I have websocket running on a node/Express server.

I need to send json string back and fourth between a websocket and a client.

However, if a user opens more than one browser's tab, I like for the websocket server to know that this is the same user that is already connected.

Here is the logic execution order

  1. A user connects to the WebSocket.
  2. The user sends json string to the WebSocket.
  3. The WebSocket does things to the received message.
  4. WebSocket finally sends the new message to all the tabs that a user have open.

The new message should be returned only to that user not others.

How can I establish one connection between a user and the WebSocket?

This is my server setup

var env = require('./config');

var app = require('express')();
var server = require('http').Server(app);

var io = require('socket.io')(server);
var clients = [];

server.listen(env.socket.port, env.socket.host, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Websocket running at http://%s:%s', host, port);
});

app.get('/', function (req, res) {
    res.send('Welcome!');
});

io.on('connection', function (socket) {

    clients[] = socket;

    socket.emit('chat', { hello: 'world' });

    socket.on('chat', function(msg){
        console.log('message: ' + msg);
        sendAll(msg);
    });

});

function sendAll (message) {
    for (var i=0; i< clients.length; i++) {
        clients[i].send("Message For All: " + message);
    }
}
Junior
  • 11,602
  • 27
  • 106
  • 212
  • that makes since. How would I send a message to every tab that belongs for 1 user? – Junior Sep 14 '15 at 20:21
  • using a session clients would be keyed by sessionid `clients = {session1: [socket]};` `clients['session1'].push(newTabSocket)` – dm03514 Sep 14 '15 at 20:25
  • I have a `PHPSESSID` cookie that I can user. But, how do I read the cookie value in the `io.on('connection', function(socket){....` – Junior Sep 14 '15 at 20:37
  • http://stackoverflow.com/questions/4754232/can-i-access-a-cookie-from-socket-io – dm03514 Sep 14 '15 at 20:39
  • Thank you again for that. But that does not give me access to the PHPSESSID cookie. – Junior Sep 14 '15 at 20:45

1 Answers1

0

If you do not have authentication for the users, then you need some browser-specific piece of data to correlate users on your backend.

I don't know about cookies (haven't used them), but one way at the JavaScript level would be to store a locally generated random ID (of sufficient length so that you don't have to worry about collisions) in local storage in the browser, and transmit this as part of the initial message at the WebSocket level.

gzost
  • 2,375
  • 1
  • 18
  • 25