Upgrade to Pro — share decks privately, control downloads, hide ads and more …

NodeJS + SocketIO

NodeJS + SocketIO

Lightning talk @ Codelovers.

Federico Ravasio

October 15, 2012
Tweet

More Decks by Federico Ravasio

Other Decks in Programming

Transcript

  1. +

  2. “In attesa di uno straniero...” “Stai parlando con uno straniero,

    salutalo!” Straniero: asl? Tu: 98 m antarctica Straniero: o_o” [Qualcuno lascia la chat]
  3. var waiting = []; // Lista client in attesa var

    couples = {}; // { // clientID: stranger, // strangerID: client // ... // }
  4. var io = SocketIO.listen(server); // server è un server HTTP

    già inizializzato io.sockets.on('connection', function(client) { // ... });
  5. io.sockets.on('connection', function(client) { if (waiting.length == 0) { waiting.push(client); client.emit('waiting');

    } else { var stranger = waiting.pop(); couples[client.id] = stranger; couples[stranger.id] = client; client.emit('partner'); stranger.emit('partner'); } // ... });
  6. io.sockets.on('connection', function(client) { // ... client.on('disconnect', function() { if (stranger

    = couples[client.id]) { stranger.emit('left'); delete couples[stranger.id]; delete couples[client.id]; } }); });
  7. var socket = io.connect(); socket.on('waiting', function() { logMessage('Waiting for a

    stranger...'); }); socket.on('partner', function() { logMessage('You are now chatting with...'); }); socket.on('message', function(message) { logMessage(message); }); socket.on('left', function() { this.logMessage('Stranger has left...'); socket.disconnect(); });
  8. var leaveConversation = function() { logMessage('You have left...'); socket.disconnect(); };

    var sendMessage = function(message) { socket.emit('message', message); logMessage(message); };