Socket.io 自定义客户端 ID

发布于 2024-12-09 01:14:26 字数 183 浏览 0 评论 0原文

我正在使用 socket.io 制作一个聊天应用程序,并且我想使用我的自定义客户端 ID,而不是默认的客户端 ID(84114736213944127071120516437992682114)。有没有什么方法可以在连接时发送自定义标识符,或者只是使用某些东西来跟踪每个 ID 的自定义名称?谢谢!

I'm making a chat app with socket.io, and I'd like to use my custom client id, instead of the default ones (8411473621394412707, 1120516437992682114). Is there any ways of sending the custom identifier when connecting or just using something to track a custom name for each ID? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

束缚m 2024-12-16 01:14:26

您可以在服务器上创建一个数组,并在其上存储自定义对象。例如,您可以存储 Socket.io 创建的 id 以及每个客户端发送到服务器的自定义 ID:

var util = require("util"),
    io = require('/socket.io').listen(8080),
    fs = require('fs'),
    os = require('os'),
    url = require('url');

    var clients =[];

    io.sockets.on('connection', function (socket) {

        socket.on('storeClientInfo', function (data) {

            var clientInfo = new Object();
            clientInfo.customId         = data.customId;
            clientInfo.clientId     = socket.id;
            clients.push(clientInfo);
        });

        socket.on('disconnect', function (data) {

            for( var i=0, len=clients.length; i<len; ++i ){
                var c = clients[i];

                if(c.clientId == socket.id){
                    clients.splice(i,1);
                    break;
                }
            }

        });
    });

在此示例中,您需要从每个客户端调用 storeClientInfo

<script>
    var socket = io.connect('http://localhost', {port: 8080});

    socket.on('connect', function (data) {
        socket.emit('storeClientInfo', { customId:"000CustomIdHere0000" });
    });
</script>

希望这有帮助。

You can create an array on the server, and store custom objects on it. For example, you could store the id created by Socket.io and a custom ID sent by each client to the server:

var util = require("util"),
    io = require('/socket.io').listen(8080),
    fs = require('fs'),
    os = require('os'),
    url = require('url');

    var clients =[];

    io.sockets.on('connection', function (socket) {

        socket.on('storeClientInfo', function (data) {

            var clientInfo = new Object();
            clientInfo.customId         = data.customId;
            clientInfo.clientId     = socket.id;
            clients.push(clientInfo);
        });

        socket.on('disconnect', function (data) {

            for( var i=0, len=clients.length; i<len; ++i ){
                var c = clients[i];

                if(c.clientId == socket.id){
                    clients.splice(i,1);
                    break;
                }
            }

        });
    });

in this example, you need to call storeClientInfo from each client.

<script>
    var socket = io.connect('http://localhost', {port: 8080});

    socket.on('connect', function (data) {
        socket.emit('storeClientInfo', { customId:"000CustomIdHere0000" });
    });
</script>

Hope this helps.

唔猫 2024-12-16 01:14:26

要设置自定义套接字 ID,generateId 函数必须被覆盖。 Socket.io server 对象的 eioengine 属性都可以用于管理此操作。

举个简单的例子:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.engine.generateId = function (req) {
    // generate a new custom id here
    return 1
}

io.on('connection', function (socket) {
    console.log(socket.id); // writes 1 on the console
})

好像已经处理好了。

必须记住,考虑到安全性和应用程序操作,套接字 ID 必须是不可预测且具有唯一值!

额外:如果由于 generateId 方法上的密集处理而导致 socket.id 返回为 undefinedasync/await 组合可用于解决 node.js 7.6.0 及更高版本上的此问题。
node_modules/engine.io/lib/server.js 文件的 handshake 方法应更改如下:

当前:

// engine.io/lib/server.js

Server.prototype.generateId = function (req) {
  return base64id.generateId();
};

Server.prototype.handshake = function (transportName, req) {
  var id = this.generateId(req);
  ...
}

新:

// function assignment

io.engine.generateId = function (req) {
  return new Promise(function (resolve, reject) {
    let id;
    // some intense id generation processes
    // ...
    resolve(id);
  });
};


// engine.io/lib/server.js

Server.prototype.handshake = async function (transportName, req) {
  var id = await this.generateId(req);
  ...
}

注意:位于Engine.io v4。 0, generateId 方法将接受回调。所以不需要改变握手方法。只需替换 generateId 方法就足够了。例如:

io.engine.generateId = function (req, callback) {
  // some intense id generation processes
  // ...
  callback(id);
};

To set custom socket id, generateId function must be overwritten. Both of eio and engine props of Socket.io server object can be used for to manage this operation.

A simple example:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.engine.generateId = function (req) {
    // generate a new custom id here
    return 1
}

io.on('connection', function (socket) {
    console.log(socket.id); // writes 1 on the console
})

It seems to be it has been handled.

It must be in mind that socket id must be unpredictable and unique value with considering security and the app operations!

Extra: If socket.id is returned as undefined because of your intense processes on your generateId method, async/await combination can be used to overcome this issue on node.js version 7.6.0 and later.
handshake method of node_modules/engine.io/lib/server.js file should be changed as following:

current:

// engine.io/lib/server.js

Server.prototype.generateId = function (req) {
  return base64id.generateId();
};

Server.prototype.handshake = function (transportName, req) {
  var id = this.generateId(req);
  ...
}

new:

// function assignment

io.engine.generateId = function (req) {
  return new Promise(function (resolve, reject) {
    let id;
    // some intense id generation processes
    // ...
    resolve(id);
  });
};


// engine.io/lib/server.js

Server.prototype.handshake = async function (transportName, req) {
  var id = await this.generateId(req);
  ...
}

Note: At Engine.io v4.0, generateId method would accept a callback. So it would not needed to change handshake method. Only generateId method replacement is going to be enough. For instance:

io.engine.generateId = function (req, callback) {
  // some intense id generation processes
  // ...
  callback(id);
};
会发光的星星闪亮亮i 2024-12-16 01:14:26

在最新的socket.io(版本1.x)中你可以这样做

socket  = io.connect('http://localhost');

socket.on('connect', function() {
    console.log(socket.io.engine.id);     // old ID
    socket.io.engine.id = 'new ID';
    console.log(socket.io.engine.id);     // new ID
});

In the newest socket.io (version 1.x) you can do something like this

socket  = io.connect('http://localhost');

socket.on('connect', function() {
    console.log(socket.io.engine.id);     // old ID
    socket.io.engine.id = 'new ID';
    console.log(socket.io.engine.id);     // new ID
});
南风起 2024-12-16 01:14:26

我会使用一个对象作为哈希查找 - 这将节省您循环遍历数组

var clients = {};
clients[customId] = clientId;

var lookup = clients[customId];

I would use an object as a hash lookup - this will save you looping through an array

var clients = {};
clients[customId] = clientId;

var lookup = clients[customId];
如果没结果 2024-12-16 01:14:26

不要将套接字 ID 更改为您自己选择的 ID,这会完全破坏 Socket.io 房间系统。它会默默地失败,您将不知道为什么您的客户没有收到消息。

Do not change the socket IDs to ones of your own choosing, it breaks the Socket.io room system entirely. It will fail silently and you'll have no clue why your clients aren't receiving the messages.

沉鱼一梦 2024-12-16 01:14:26

这适用于 2.2.0 及以上版本的 Socket.IO

要设置自定义 Socket Id,必须覆盖 generateId 函数。

一个简单的示例:

服务器端

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.use((socket, next) => {
  io.engine.generateId = () => {
    // USE ONE OF THESE
    socket.handshake.query.CustomId; // this work for me
    // return socket.handshake.query.CustomId;
  }
  next(null, true);
});

io.on('connection', function (socket) {
    console.log(socket.id);
})

客户端端

io.connect(URL, { query: "CustomId = CUSTOM ID IS HERE" })

注意:请记住,套接字 ID 必须是唯一值。

This will work with 2.2.0 and above version of Socket.IO

To set custom Socket Id, generateId function must be overwritten.

A simple example:

Server Side

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.use((socket, next) => {
  io.engine.generateId = () => {
    // USE ONE OF THESE
    socket.handshake.query.CustomId; // this work for me
    // return socket.handshake.query.CustomId;
  }
  next(null, true);
});

io.on('connection', function (socket) {
    console.log(socket.id);
})

Clint Side

io.connect(URL, { query: "CustomId = CUSTOM ID IS HERE" })

NOTE: Keep in mind that socket id must be a unique value.

‖放下 2024-12-16 01:14:26

为什么不是一个更简单的解决方案,不需要维护连接的客户端数组,并且不覆盖内部套接字 ID?

io.on("connection", (socket) => {
    socket.on('storeClientInfo', (data) => {
        console.log("connected custom id:", data.customId);
        socket.customId = data.customId;
    });

    socket.on("disconnect", () => {
        console.log("disconnected custom id:", socket.customId);
    })
});

客户端

let customId = "your_custom_device_id";
socket.on("connect", () => {
    socket.emit('storeClientInfo', { customId: customId });
});

why not a simpler solution that does not need to maintain an array of connected clients and does not override internal socket id?

io.on("connection", (socket) => {
    socket.on('storeClientInfo', (data) => {
        console.log("connected custom id:", data.customId);
        socket.customId = data.customId;
    });

    socket.on("disconnect", () => {
        console.log("disconnected custom id:", socket.customId);
    })
});

Client side

let customId = "your_custom_device_id";
socket.on("connect", () => {
    socket.emit('storeClientInfo', { customId: customId });
});
提赋 2024-12-16 01:14:26

或者您可以覆盖套接字 ID,如下所示:

io.on('connection', function(socket){

      socket.id = "YOUR_CUSTOM_ID";
});

您可以在数组下看到:

io.sockets.sockets

or you can override the socket id, like this:

io.on('connection', function(socket){

      socket.id = "YOUR_CUSTOM_ID";
});

you can see under the array:

io.sockets.sockets

_蜘蛛 2024-12-16 01:14:26

可以以对象格式存储customId(例如userId)而不是for循环,这将提高连接、断开连接和检索socketId以发出

`期间的性能

 var userId_SocketId_KeyPair = {};
 var socketId_UserId_KeyPair = {};

_io.on('connection', (socket) => {
    console.log('Client connected');
    //On socket disconnect
    socket.on('disconnect', () => {
        // Removing sockets
        let socketId = socket.id;
        let userId = socketId_UserId_KeyPair[socketId];
        delete socketId_UserId_KeyPair[socketId];
        if (userId != undefined) {
            delete userId_SocketId_KeyPair[userId];
        }
        console.log("onDisconnect deleted socket with userId :" + "\nUserId,socketId :" + userId + "," + socketId);
    });

    //Store client info
    socket.on('storeClientInfo', function (data) {
        let jsonObject = JSON.parse(data);
        let userId = jsonObject.userId;
        let socketId = socket.id;
        userId_SocketId_KeyPair[userId] = socketId;
        socketId_UserId_KeyPair[socketId] = userId;
        console.log("storeClientInfo called with :" + data + "\nUserId,socketId :" + userId + "," + socketId);
    });
`

Can store customId (example userId) in object format instead of for loop, this will improve performance during connection, disconnect and retrieving socketId for emitting

`

 var userId_SocketId_KeyPair = {};
 var socketId_UserId_KeyPair = {};

_io.on('connection', (socket) => {
    console.log('Client connected');
    //On socket disconnect
    socket.on('disconnect', () => {
        // Removing sockets
        let socketId = socket.id;
        let userId = socketId_UserId_KeyPair[socketId];
        delete socketId_UserId_KeyPair[socketId];
        if (userId != undefined) {
            delete userId_SocketId_KeyPair[userId];
        }
        console.log("onDisconnect deleted socket with userId :" + "\nUserId,socketId :" + userId + "," + socketId);
    });

    //Store client info
    socket.on('storeClientInfo', function (data) {
        let jsonObject = JSON.parse(data);
        let userId = jsonObject.userId;
        let socketId = socket.id;
        userId_SocketId_KeyPair[userId] = socketId;
        socketId_UserId_KeyPair[socketId] = userId;
        console.log("storeClientInfo called with :" + data + "\nUserId,socketId :" + userId + "," + socketId);
    });
`
聽兲甴掵 2024-12-16 01:14:26

使用 Socket.IO 2.2.0 版本,您可以实现这一目标。

io.use((socket, next) => {
  io.engine.generateId = () => socket.handshake.query.token;
  next(null, true);
});

With this 2.2.0 version of Socket.IO, you can achieve this.

io.use((socket, next) => {
  io.engine.generateId = () => socket.handshake.query.token;
  next(null, true);
});
梦幻的心爱 2024-12-16 01:14:26

如果您尝试使用自定义 ID 来与特定客户端进行通信,那么您可以这样做

io.on('connection', function(socket){
    socket.id = "someId"
    io.sockets.connected["someId"] = io.sockets.connected[socket.id];

    // them emit to it by id like this
    io.sockets.connected["someId"].emit("some message", "message content")
});

If you are trying to use a custom id to in order to communicate with a specific client then you can do this

io.on('connection', function(socket){
    socket.id = "someId"
    io.sockets.connected["someId"] = io.sockets.connected[socket.id];

    // them emit to it by id like this
    io.sockets.connected["someId"].emit("some message", "message content")
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文