Domanda

I am trying to get the language the user uses in order to serve the right sound files for a playing video, using socket.io and node.js. I am a total beginner with node.js and socket.io. I got the language on client side with "navigator.language" and wanted to send it when connecting/handshaking to socket.io.

var language = navigator.language;
var socket = io.connect('http://localhost:1337', { query: language });

And on server-side:

io.set('authorization', function(handshakeData, cb) {
    console.log(handshakeData.query);
    cb(null, true);});

But what I get is:

{'en-US': 'undefined', t: '1396002389530'}

I guess the second attribute "t" is the handshake ID that has been added. But how do I access 'en-US'?


My second approach was to use the module "locale" (https://github.com/jed/locale), but when I used that, I always got the same language, so I figured that it always finds the SERVER's language. I thought I use it in the request/response handler, when a new client requests the page and sends its http header.

var handler = function(req, res) {
    lang = new locale.Locales(req.headers["accept-language"]);
    lang=lang.best(supported);
    console.log(pf);
}

I hope you get what I am trying to do and maybe know a better solution. Thank you in advance.

È stato utile?

Soluzione

You're almost there. Do this:

var socket = io.connect('http://localhost:1337', { lang: language });

Instead of {query: language} because query is a reserved object.

And you can access this by doing this:

io.set('authorization', function(handshakeData, cb) {
console.log(handshakeData.query.lang);
cb(null, true);});

You can also access it like this:

io.sockets.on('connection', function(socket){
  console.log(socket.handshake.query.lang);
});

If you don't want to append language variable to query then you can access the language by this:

io.sockets.on('connection', function(socket){
  console.log(socket.handshake.headers['accept-language']);
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top