“Info - socket.io started” Missing

2019-07-21 05:38发布

问题:

I'm trying to add a socket to my app and normally if everything goes well, I should be seeing something similar to this:

info  - socket.io started
Listening { address: '0.0.0.0', family: 'IPv4', port: 443 }

However, all I'm seeing is this:

Listening { address: '0.0.0.0', family: 'IPv4', port: 443 }

Which can only means that the socket is not working. Here's my socket code:

var sockets = require('socket.io').listen(server).of('/elyes');

sockets.use(function (socket, next) {
  // Read cookies from handshake headers
  var handshakeData = socket.request;
  var cookies = cookie.parse(handshakeData.headers.cookie);
  // We're now able to retrieve session ID
  var sessionID;
  if (cookies['connect.sid']) {
    sessionID = connect.utils.parseSignedCookie(cookies['connect.sid'], sessionSecret);
  }
  // No session? Refuse connection
  if (!sessionID) {
    callback('No session', false);
  } else {
    // Store session ID in handshake data, we'll use it later to associate
    // session with open sockets
    handshakeData.sessionID = sessionID;
    // On récupère la session utilisateur, et on en extrait son username
    sessionStore.get(sessionID, function (err, session) {
      if (!err && session && session.username) {
        // On stocke ce username dans les données de l'authentification, pour réutilisation directe plus tard
        handshakeData.username = session.username;
        handshakeData['pwdHash']=session.pwdHash;
        // OK, on accepte la connexion
        callback(null, true);
      } else {
        // Session incomplète, ou non trouvée
        callback(err || 'User not authenticated', false);
      }
    });
  }
});

var connections = {};
sockets.on('connection', function (socket) { // New client

    //========================================================= 
    socket.handshake['socket']=socket;
    socket.handshake['sockets']=sockets;
    connectedClients[socket.handshake.pwdHash]=socket.handshake
    //console.log(connectedClients);
    //=========================================================

    broadcastToClients=sockets;
    if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
        //console.log(sockets['checkConnectivityInterval']);
        if (connectedClients[socket.handshake.pwdHash].checkConnectivityInterval!=undefined) 
            clearInterval(connectedClients[socket.handshake.pwdHash].checkConnectivityInterval);
            if (connectedBoxs[socket.handshake.pwdHash].stream!=undefined) 
            connectedClients[socket.handshake.pwdHash]['checkConnectivityInterval']=setInterval(function(){connectedBoxs[socket.handshake.pwdHash].stream.push('PresenceCheck\n')
                                                                                                            }, 2000); 
        //console.log(sockets['checkConnectivityInterval']);
    }
    else{
        sockets.emit('isBoxOnline', false);
    }

    //numClient++;
    //connectedClients[numClient]=socket;
  //socket.emit('message', Date.now());
  var sessionID = socket.handshake.sessionID; // Store session ID from handshake
  //console.log(socket.handshake);
  // this is required if we want to access this data when user leaves, as handshake is
  // not available in "disconnect" event.
  var username = socket.handshake.username; // Same here, to allow event "bye" with username
  if ('undefined' == typeof connectedClients[sessionID]) {
    connectedClients[sessionID] = { "length": 0 };
    // First connection
    sockets.emit('join', username, Date.now());
  }
  // Add connection to pool
  connectedClients[sessionID][socket.id] = socket;
  connectedClients[sessionID].length ++;


  // When user leaves
    socket.on('disconnect', function () {
       // Is this socket associated to user session ?
       var userConnections = connectedClients[sessionID];
       if (userConnections.length && userConnections[socket.id]) {
         // Forget this socket
         userConnections.length --;
         delete userConnections[socket.id];
       }
       if (userConnections.length == 0) {
        console.log("================================");
         // No more active sockets for this user: say bye
           if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
if (connectedClients[socket.handshake.pwdHash].checkConnectivityInterval!=undefined) 
            clearInterval(connectedClients[socket.handshake.pwdHash].checkConnectivityInterval);  
           }
         delete connectedClients[socket.handshake.pwdHash];
         sockets.emit('bye', username, Date.now());
       }
     });

    socket.on('isBoxOnline', function(message){
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            socket.emit('isBoxOnline', true);
        }
        else{
            socket.emit('isBoxOnline', false);
        }
    });

    socket.on('getConnectedDevices', function(message){
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            connectedBoxs[socket.handshake.pwdHash].stream.push('ConnectedDevices\n');
            console.log(['Here GetBoxStatus Function !'].join("\n").green);
        }    
    });

    socket.on('Mount', function(message){
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            connectedBoxs[socket.handshake.pwdHash].stream.push('Mount'+message+'\n');
        }    
    });

    socket.on('Umount', function(message){
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            connectedBoxs[socket.handshake.pwdHash].stream.push('Umount'+message+'\n');
        }
    });

    socket.on('RqForTree', function(message){
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            connectedBoxs[socket.handshake.pwdHash].stream.push('RqForTree'+message+'\n');
        }
    });

    socket.on('ls', function(message){
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            connectedBoxs[socket.handshake.pwdHash].stream.push('ls'+message+'\n');
        }
    });

    socket.on('Download', function(message){
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            connectedBoxs[socket.handshake.pwdHash].stream.push('Download'+message+'\n');
        }
    });

    socket.on('getBoxStatus', function (message) {
     if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
        connectedBoxs[socket.handshake.pwdHash].stream.push(['Here GetBoxStatus Function !\n'].join("\n").green);
        console.log(['Here GetBoxStatus Function !'].join("\n").green);
     }
    });

    socket.on('message1', function (message) {
        if (connectedBoxs[socket.handshake.pwdHash]!=undefined) {
            connectedBoxs[socket.handshake.pwdHash].stream.push("message1\n");
            //console.log("//==============================================");
            //console.log(connectedBoxs[socket.handshake.pwdHash].stream);
            //console.log("//==============================================");
        }
    });

  // New message from client = "write" event
  socket.on('write', function (message) {
    sockets.emit('message', username, message, Date.now());
  });
});

if (!module.parent) {
  server.listen(port, function () {
    console.log('Listening', this.address());
  })
}

What am I doing wrong here?

回答1:

It turns out it was just a version issue:

info messages like "info - socket.io started" don't show up in 1.0 versions, only in 0.* versions. So if you're running a 0.* socket.io code while having a 1.0 socket.io version in your package.json, what you need to do is:

  • The quickest way is to install the same version in your package.json:

    npm install socket.io@insert.your.version.here

  • Or keep your up-to-date socket.io version and edit your code accordingly. Like for instance:

    io.set('authorization', function (handshakeData, callback) { Becomes:

    io.use(function(socket, next) { var handshakeData = socket.request;

I'd recommend this article on how to migrate to 1.0: socket.io/docs/migrating-from-0-9/