Node.js - Socket.io repeats the 'io.on('connection') over and over

D. Dog :

So, I am still in the experimental phase of Socket.io, but I just can't figure out why my code is doing this. So, I have the code below and when I console.log the code, it repeats the the connection even when there is only one connection. Do you know a solution?

io.on('connnection', (socket) => {
    console.log("A new user is connected.")
})

Client side:

<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io()
</script>

Node.js Console:

A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
A new user is connected.
...

(Note: there is only one connection, and I have already cleared the browser cashe)

jfriend00 :

Here are some of the possible reasons for socket.io connecting over and over:

  1. Your socket.io client and server versions do not match and this causes a connection failure and an immediate retry.

  2. You are running with some infrastructure (like a proxy or load balancer) that is not configured properly to allow lasting webSocket connections.

  3. You are running a clustered server without sticky webSocket connections.

  4. You have put the server-side io.on('connnection', ...) code inside some other function that is called more than once causing you to register multiple event handlers for the same event so you think you're getting multiple events, but actually you just have multiple listeners for the one occurrence of the event.

  5. Your client code is calling its var socket = io() more than once.

FYI, you can sometimes learn something useful by installing listeners for all the possible error-related events on both client and server connections and then logging which ones occur and any parameters that they offer. You can see all the client-related error events you can listen to and log here.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=404926&siteId=1