How to best send additional data upon socket connection?
Client:
socket.on('connect',function(){
//I'd like set some values and pass them up to the node server.
});
Node.js Server:
io.on('connection', function(client){
//I'd like to get the data here.
});
For example sending a user name or email address etc.
The
connection
events get fired as soon as the TCP connection is established. There's no way to send anything in between.What you can do is to simply take the first message send by the server and put the data in that message. I'd strongly suggest to roll some thin protocol for this, so you would have multiple types of messages and use those to determine how the code should process the data.
This would be more extendable too, since it's fairly easy to come up with a generic architecture for that. If you want to wait for the
userdata
to come in first you can simply add some state to your connections.this is my code on socket version 2.1.1
I have a different approach - emit an event right after connecting, with the data:
You can hold a variable/object, and say, when there is no
ehlo
event with data, the other events are ignored untilehlo
is sent.If this does not satisfy, you can send data right when connecting, I won't copy the code but it is in this answer: https://stackoverflow.com/a/13940399/1948292
I found the answer located here really helpful in this regard: Send custom data along with handshakeData in socket.io?
Also brushing up on the following documentation helps explain ways to tie variables to the handshake object which can be accessed from the socket object during the connection: https://github.com/LearnBoost/socket.io/wiki/Authorizing#global-authorization
You should send your data either in connect or on create:
With the new version of socket.io, on server is where the things have been changed:
this my code for sending query data to nodejs and server.io server client
query...user1