wbruno / livro-nodejs

Livro de NodeJS
https://novatec.com.br/livros/nodejs-4ed/
MIT License
106 stars 33 forks source link

Capítulo 2 - chat TCP #5

Closed gabsprates closed 7 years ago

gabsprates commented 7 years ago

Olá,

Confesso que não entendi o clientList.indexOf(5) da linha 8 no arquivo do chat.

Isso está certo? Deveria ser 5 mesmo ou era pra ser algo relacionado à variável data do escopo dessa função?

wbruno commented 7 years ago

Oi @gabsprates ! foi erro meu.. o correto é assim:

'use strict';

var net         = require('net'),
    chatServer  = net.createServer(),
    clientList  = [];

var broadcast = function (message, client) {
  for (var i = clientList.length - 1; i >= 0; i--) {
    if (client !== clientList[i]) {
      clientList[i].write(message);
    }
  }
};

chatServer.on('connection', function (client) {
  client.write('Hi guest' + '!\n');
  clientList.push(client);

  client.on('data', function (data) {
    broadcast(data, client);
  });
  client.on('end', function () {
    console.log('client', clientList.indexOf(client));

    clientList.splice(clientList.indexOf(client), 1);
  });
  client.on('error', function(err) {
    console.log(err);
  });
});

chatServer.listen(9000);
gabsprates commented 7 years ago

Ah sim! Agora eu entendi (: Obrigado.

Onde eu acho uma lista com os eventos .on() do net.createServer();?

wbruno commented 7 years ago

aqui: https://nodejs.org/dist/latest-v7.x/docs/api/net.html

gabsprates commented 7 years ago

Opa, eu não tinha reparado nas seções "Event: " :laughing:

Valeu (: