我正在实现一个node.js服务器,该服务器使用socket.io(版本:0.8.7)管理用户之间的双连接.我使用的数组存储没有聊天伙伴的用户.当用户请求新的合作伙伴时,应用程序会选择此阵列中的用户,然后检查该用户是否仍处于连接状态.这是我的问题:
即使用户仍然连接,我也无法为用户设置套接字客户端.这是我的代码片段:
// An array of users that do not have a chat partner
var soloUsers = [];
var io = sio.listen(app);
io.sockets.on('connection', function (socket) {
socket.on('sessionStart', function (message)
{
// Parse the incoming event
switch (message.event) {
// User requested initialization data
case 'initial':
...
// User requested next partner
case 'next':
// Create a "user" data object for me
var me = {
sessionId: message.data.sessionId,
clientId: socket.sessionid
};
var partner;
var partnerClient;
// Look for a user to partner with in the list of solo users
for (var i = 0; i < soloUsers.length; i++)
{
var tmpUser = soloUsers[i];
// Make sure our last partner is not our new partner
if (socket.partner != tmpUser)
{
// Get the socket client for this user
partnerClient = io.sockets.clientsIndex[tmpUser.clientId];
// Remove the partner we found from the list of solo users
soloUsers.splice(i, 1);
// If the user we found exists...
if (partnerClient)
{
// Set as our partner and quit the loop today
partner = tmpUser;
break;
}
}
}
...
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
partnerClient = io.sockets.clientsIndex[clientId];
^
TypeError: Cannot read property 'undefined' of undefined
Run Code Online (Sandbox Code Playgroud)
我做了clientId的输出(console.log),它肯定是未定义的.此外,我认为socket.io版本0.8中的API可能已更改,您不能再使用"clientsIndex"方法.有谁知道更换?
谢谢!!!
最好的办法是跟踪对象中连接的客户端.以下是我将如何实现这一目标:
var clients = {};
io.sockets.on('connection', function (socket) {
// remember the client by associating the socket.id with the socket
clients[socket.id] = socket;
socket.on('sessionStart', function (message) {
// get the socket.id of the partner on each message
var partner = message.from;
if (clients[partner]) {
// check if the partner exists and send a message to the user
clients[socket.id].emit('message', { from: partner, msg: message });
}
}
socket.on('disconnect', function() {
delete clients[socket.id]; // delete the client from the list
});
}
Run Code Online (Sandbox Code Playgroud)
注意:在实际的生产应用程序中,您通常会检查会话数据并将每个客户端与用户名和socket.id相关联.
| 归档时间: |
|
| 查看次数: |
5690 次 |
| 最近记录: |