2017-08-31 8 views
0

Ich bin mit socket.io auf node.js (Client und Server) herumspielen, und Probleme mit dem Ereignis "Trennen". Werfen Sie einen Blick auf die folgenden Mokka Testcode:Socket.io Server nicht "Trennen" -Ereignis empfangen, wenn Client-Aufrufe trennen

it('This test never finishes', function(done) { 
     // Output: 
     // connected socket iYTGdwMJ0yVM5orGAAAB 

     io.on('connection', (socket) => { 
     console.log('connected socket', socket.id); 
     socket.on('disconnect',() => { 
      console.log('io disconnect'); 
      done(); 
     }); 
     }); 

     const mj = ioClient(`https://localhost:${socketPort}`); 

     mj.on('disconnect',() => { 
     console.log('mj disconnect'); 
     }); 

     mj.disconnect(); 
    }); 

    it('This test works', function(done) { 
     // Output: 
     // connected socket DNUREuytEp1CPJdFAAAC 
     // io disconnect 

     io.on('connection', (socket) => { 
     console.log('connected socket', socket.id); 
     console.log(io.socket.connected); 
     socket.on('disconnect',() => { 
      console.log('io disconnect'); 
      done(); 
     }); 
     socket.disconnect(); 
     }); 

     const mj = ioClient(`https://localhost:${socketPort}`); 

     mj.on('disconnect',() => { 
     console.log('mj disconnect'); 
     }); 

     // Looks like this has no effect 
     mj.disconnect(); 
    }); 
    }); 

Wenn disconnect auf dem Client aufgerufen wird, warum der Server nicht lösen die socket.on('disconnect', ...) Zuhörer?

+0

Haben Sie versucht, andere Verbindung mit Client und Server zu machen? Kommunizieren sie überhaupt? Versuchen Sie, einen Test auszugeben 'socket.emit ('test', true)' dann sehen Sie, ob Sie es erhalten – forJ

+0

@serendipity ja, das funktioniert. – PunDefeated

Antwort

2

Ich denke, das ist ein typisches Synchronitätsproblem (lesen Erklärungen in Code Kommentare).

// This code will try to connect the server - 
// but the connection process is asynchronous 
const mj = ioClient(`https://localhost:${socketPort}`); 

// Now you subscribe to the disconnect event which is fine 
mj.on('disconnect',() => { 
    console.log('mj disconnect'); 
}); 

// And now you try to disconnect immediately which is done synchronously 
// but how do you want to disconnect since you are still not connected ... 
mj.disconnect(); 

Was Sie tun können, ist zu trennen, um zu versuchen, wenn Sie sicherstellen, dass Sie verbunden sind :)

const mj = ioClient(`https://localhost:${socketPort}`); 

mj.on('connect',() => { 

    // Subscribe to disconnect event once you know you are connected 
    mj.on('disconnect',() => { 
     console.log('mj disconnect'); 
    }); 

    // Now disconnect once you are connected 
    mj.disconnect(); 
}); 
+0

Nun, ich fühle mich nicht albern! Vielen Dank :) – PunDefeated

+0

Sie sind herzlich willkommen :) – codtex

Verwandte Themen