将函数参数保存到node.js中从socket.on传入的全局变量

时间:2019-01-16 06:49:22

标签: node.js sockets

我正在处理一个任务,以创建一个聊天模块,该模块在Android Studio IDE中使用socket.io,node.js,java。

我了解了基础知识,并能够创建基本的聊天室以与多个用户进行群聊。但我想让它的用户到用户。为此,我在node.js中使用了套接字ID列出了所有连接的客户端。但这还不够,要向客户端发出此列表,我需要为每个连接的套接字ID提供一个用户名,以便可以将socket.id与相应的用户名结合起来并放入列表中。

我被困在中间,无法确定如何使来自socket.on(event, function(string))的字符串能够被全局访问。我试图将这个字符串推到一个数组中,并在socket.on之后访问它,但是什么也没发生。

这是我的代码

index.js

const express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.get('/', (req, res) => {

res.send('Chat Server is running on port 4040')
});

io.on('connection', (socket) => {

console.log('user connected');
console.log("The socket id is " + socket.id);

socket.on('join', function(userNickname) {
    console.log("User" + userNickname +" : has joined the chat ");
    io.sockets.emit('userjoinedthechat',userNickname +" : has joined the chat ");

    });


var req = io.sockets.connected;
var count = Object.keys(req).length;
console.log(socket);
console.log("Number of connected clients: " + count);
var list = new Array();
for(var i = 0; i < count; i++) {
    user = Object.keys(req)[i];
    list.push("User Id : " + user, "User Name : ");
}
console.log("Connected Clients Socket Id's: " + list);
io.sockets.emit('users', list);
});

我正在尝试的是

//Declare a global variable or array
var user;
//(or)
var users = new Array();

socket.on('join', function(userNickname) {
    console.log("User" + userNickname +" : has joined the chat ");
    user = userNickname;
    //(or)
    users.put(userNickname);
    io.sockets.emit('userjoinedthechat', userNickname +" : has joined the chat ");
    });

并在外部访问它,

console.log(user);    //global variable
//or
console.log(users);   //Array list

任何帮助都会很棒。谢谢。

1 个答案:

答案 0 :(得分:1)

类似的东西应该可以工作:

//Declare a global variable or array
var user;
var users = [];

socket.on('join', function(userNickname) {
    console.log("User" + userNickname +" : has joined the chat ");
    user = userNickname;
    users.push(userNickname);
    io.sockets.emit('userjoinedthechat', userNickname +" : has joined the chat ");
    console.log("User list: ", users);
});

保存用户时,每次有人加入时它都会更新,因此它实际上是最新加入的用户(您可以将其更改为LatestUser或类似名称)。

users数组将在全局范围内可用,但是请注意console.log语句的顺序。如果在紧接socket.on('join')..调用之后发出console.log,请记住,最初会看到一个空列表。