[英]Extra params with socket.io
How can I send extra parameters with the connection in socket.io?如何通过 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).首先,您创建自己的 Socket 客户端,在第一次连接时发送消息(包含所有附加信息)。
// 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.这是我用来将我的 session 处理链接到 Socket.IO 的技术,用于我写的 package。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.