为什么套接字连接计数器没有更新? [英] why isn't the socket connection counter updating?

查看:35
本文介绍了为什么套接字连接计数器没有更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 index.html(客户端)中的代码.我想知道为什么这个数字没有增加.我希望每次连接套接字时我都会给它一个唯一的名称.

this is the code I have in an index.html (client). Im wondering why the number is not being incremented. I expect on each time a socket connect I give it a unique name.

 var number = 0;

    socket.on("connect",function(){
         number = number+1;

        socket.emit("add user","user"+ number )


    })

但是当我有了这个服务器

but when i have this server

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

    console.log("io.onconnection")
    socket.on("add user", function(data){ 
    console.log(data)
    })
});

在每次连接时,我都会记录user1为什么不是第二个连接user2?谢谢

on each connection i get logged user1, why isn't the second connection user2? thanks

推荐答案

因为 javascript 是客户端,每次页面刷新/加载时 number 总是为 0.

Because javascript is a client side, and number will always be 0 every time the page refresh/load.

您可以计算在您的 websocket 中连接的客户端数量,服务器然后将其传递给 js,然后您可以递增.

You can count the number client connected in your websocket, server then pass it to js and then you can increment.

这篇关于为什么套接字连接计数器没有更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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