Extra params with socket.io
How can I send extra parameters with the connection in socket.io? So when a client connects, they send additional information, 开发者_运维知识库and server-side it is received as
io.on('connection', function(client, param1, param2, param3) {
// app code
}
Here's a little trick which should work. First, you create your own Socket client that sends a message on first connection (containing all your additional info).
// Client side
io.MySocket = function(your_info, host, options){
io.Socket.apply(this, [host, options]);
this.on('connect', function(){
this.send({__special:your_info});
});
};
io.util.inherit(io.MySocket, io.Socket);
var my_info = {a:"ping"}
var socket = io.MySocket(my_info);
Then on the server side, you modify your socket to listen for the special message and fire off an event when it does.
// Server side
var io = require('socket.io').listen(app);
io.on('connection', function(client){
client.on('message', function(message){
if (message.__special) {
io.emit('myconnection', client, message.__special);
}
});
});
io.on('myconnection', function(client, my_info) {
// Do your thing here
client.on('message', ...); // etc etc
}
This is the technique I used to link my session handling into Socket.IO for a package I wrote.
精彩评论