socket.io / parameters on connection

Yes, there is.

1) query is like GET parameters, so replace "param:value" with "param=value" (if you want to pass multiple parameters, do it as you usually do with URL: param=value&some_other_param=test)

2) There is an easier and more reliable (because there is no risk to access an undefined property of handshaken object) way to get query parameter inside connection handler:

console.log(socket.handshake.query.param);

Edit:

After learning your full code I guess I figured out what causes the problem. The problem is that you probably misunderstood the main idea of Socket.IO namespaces.

I guess you have multiple Socket.IO connections (io.connect calls) within one page, right? Usually a single connection is enough. Your mistake is that you call io.connect on mouse event, but you should call in once on document.ready, and then just emitting.

Take a look at the following code (client side):

$(document).ready(function() {
    var socket = io.connect('', {query: 'name=something'});

    // [...]

    socket.on('some_event_from_server', function(data, cb) {});

    // [...]

    $('#someButton').click(function() {
        socket.emit('markers_add', {some: 'data'});  //send `markers_add` message to server within main namespace
    });

    $('#someOtherButton').click(function() {
        socket.emit('icon_sets_add', {some: 'thing'}, function(response) {
            //server may response to this request. see server side code below
        });
    });
});

Server side code:

io.on('connection', function(socket) {  //connection handler of main namespace
    socket.on('markers_add', function(data) { /* ... */  });
    socket.on('icon_sets_add', function(data, cb) {
        // do something
        cb({some: 'response'});
    });

    // [...]

    socket.emit('some_event_from_server', {});  //server sends a message to a client

    //BTW, now it should be OK:
    console.log(socket.handshake.query.name);
});

If you have one namespace it should work. I don’t know actually if it was a bug of Socket.IO or a result of improper usage of namespaces, but modifying code to make just one namespace should do the trick. So in your case you don’t have to pass query parameters when handshaking at all. Actually you have to use query parameter if you want to make your app more secure. See http://wlkns.co/node-js/socket-io-authentication-tutorial-server-and-client/ (for Socket.io 0.9)

Hope my answer helps you. Good luck!

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)