简体   繁体   English

Socket.io连接不止一次

[英]Socket.io connects more than once

I'm trying to display my connection to a page with socket, but when I reload my page, the message is displayed 2 times, when i reload again, 3 times etc ... 我正在尝试显示与带有套接字的页面的连接,但是当我重新加载页面时,该消息显示2次,再次重新加载时,该消息显示3次,等等。

Here is the code node js. 这是代码节点js。

.get('/compte/', function(req, res) {
res.render('compte.ejs');
io.sockets.on('connection', function(socket){
    socket.on("new_client", function(message){
       console.log(message);
    });
});

}); });

Here is the code html / script. 这是代码html /脚本。

<script src="/socket.io/socket.io.js"></script>
    <script>
        var socket = io.connect('http://localhost:8080');

        socket.emit('new_client', "hello");
    </script>

and here is the displaying after 2 reload. 这是2次重新加载后的显示。

hello

hello
hello

hello
hello
hello

I hope to have been clear about my problem. 我希望清楚我的问题。 Thank you. 谢谢。

Actually, your client does not connect more than once, but you add an event listener for SocketIO connections on each get request of /compte/ . 实际上,您的客户端连接不会超过一次,但是您会在/compte/每个get请求上为SocketIO连接添加一个事件侦听器。 They are accumulated in io.sockets . 它们累积在io.sockets

Try moving the SocketIO event handler out of the request handler: 尝试将SocketIO事件处理程序移出请求处理程序:

.get('/compte/', function(req, res) {
    res.render('compte.ejs');
});

io.sockets.on('connection', function(socket){
    socket.on("new_client", function(message){
       console.log(message);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM