与socket.io的额外参数 [英] Extra params with socket.io

查看:131
本文介绍了与socket.io的额外参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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
}


推荐答案

这是一个应该有效的小技巧。首先,您创建自己的Socket客户端,在第一次连接时发送消息(包含所有附加信息)。

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
}

这是我用来将会话处理链接到的技术我写的包的Socket.IO。

This is the technique I used to link my session handling into Socket.IO for a package I wrote.

这篇关于与socket.io的额外参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆