Question

I am trying to build a tcp chat server with following code -

var net = require("net");

Array.prototype.remove = function(e) {
  for (var i = 0; i < this.length; i++) {
    if (e == this[i]) { return this.splice(i, 1); }
  }
};

function Client(stream) {
  this.name = null;
  this.stream = stream;
}

var clients = [];

var server = net.createServer(function (stream) {
  var client = new Client(stream);
  clients.push(client);

  stream.setTimeout(0);
  stream.setEncoding("utf8");

  stream.addListener("connect", function () {
    stream.write("Welcome, enter your username:\n");
  });

  stream.addListener("data", function (data) {
    if (client.name == null) {
      client.name = data.match(/\S+/);
      stream.write("===========\n");
      clients.forEach(function(c) {
        if (c != client) {
          c.stream.write(client.name + " has joined.\n");
        }
      });
      return;
    }

    var command = data.match(/^\/(.*)/);
    if (command) {
      if (command[1] == 'users') {
        clients.forEach(function(c) {
          stream.write("- " + c.name + "\n");
        });
      }
      else if (command[1] == 'quit') {
        stream.end();
      }
      return;
    }

    clients.forEach(function(c) {
      if (c != client) {
        c.stream.write(client.name + ": " + data);
      }
    });
  });

  stream.addListener("end", function() {
    clients.remove(client);

    clients.forEach(function(c) {
      c.stream.write(client.name + " has left.\n");
    });

    stream.end();
  });
});

server.listen(7000);

But whenever I am trying to connect to this tcp server with

nc localhost 7000 

or

telnet localhost 7000

connect block is not getting executed.

stream.addListener("connect", function () {
        stream.write("Welcome, enter your username:\n");
      });

I have also tried to connect to this tcp server with small iOS code but but no luck.

Any idea when/how this connect block will get executed?

Note: I am new to node.js and using mac os x.

Was it helpful?

Solution

First of all it should be connection event.

The function passed to createServer becomes the event handler for the 'connection' event.

var server = net.createServer(function (stream) {
  //if you are here you are already connected
});

If you want to listen for connection event do it like this -

var server = net.createServer(function (stream) {
  //your code
});

server.addListener("connection", function () {
    console.log("connected");    
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top