为什么套接字连接计数器不更新?
why isn't the socket connection counter updating?
这是我在 index.html(客户端)中的代码。我想知道为什么数字没有增加。我希望每次套接字连接时我都会给它一个唯一的名称。
var number = 0;
socket.on("connect",function(){
number = number+1;
socket.emit("add user","user"+ number )
})
但是当我有这个服务器时
io.on("connection", function(socket){
console.log("io.onconnection")
socket.on("add user", function(data){
console.log(data)
})
});
在每个连接上我都会记录 user1
,为什么 不是第二个连接 user2
?谢谢
因为javascript是client端,每次页面refresh/load时number永远为0。
你可以统计你的websocket中连接的客户端数量,服务器然后将它传递给js然后你可以递增。
这是我在 index.html(客户端)中的代码。我想知道为什么数字没有增加。我希望每次套接字连接时我都会给它一个唯一的名称。
var number = 0;
socket.on("connect",function(){
number = number+1;
socket.emit("add user","user"+ number )
})
但是当我有这个服务器时
io.on("connection", function(socket){
console.log("io.onconnection")
socket.on("add user", function(data){
console.log(data)
})
});
在每个连接上我都会记录 user1
,为什么 不是第二个连接 user2
?谢谢
因为javascript是client端,每次页面refresh/load时number永远为0。
你可以统计你的websocket中连接的客户端数量,服务器然后将它传递给js然后你可以递增。