Node js - Socket.io-client is not connecting to socket.io server

前端 未结 4 441
闹比i
闹比i 2021-01-01 16:11

I am trying to connect to a socket.io-client using the following code:

Server:

// Load requirements
var http = require(\'http\'),
    io = require(\'         


        
4条回答
  •  不知归路
    2021-01-01 16:27

    Assuming you are using a socket.io version greater than 1.0, on the server, change this:

    // Add a connect listener
    io.sockets.on('connection', function(socket) {
    
        console.log('Client connected.');
    
        // Disconnect listener
        socket.on('disconnect', function() {
            console.log('Client disconnected.');
        });
    });
    

    to this:

    // Add a connect listener
    io.on('connection', function(socket) {
    
        console.log('Client connected.');
    
        // Disconnect listener
        socket.on('disconnect', function() {
            console.log('Client disconnected.');
        });
    });
    

    See the socket.io documentation reference here.


    You don't want to be listening for this event only on already connected sockets. You want to listen for this event on any socket, even a newly created one.


    Also, be very careful when reading socket.io code in random places on the internet. Some things changed significantly from v0.9 to v1.0 (I don't know if this was one of those things or not). You should generally always start with the socket.io documentation site first since that will always represent the latest version. Then, if looking at other internet references, make sure you only use articles that are later than mid-2014. If you don't know the vintage of an article, it's best not to rely on it without corroboration from a more recent article.

提交回复
热议问题