0

我正在尝试使用以下代码构建一个 tcp 聊天服务器 -

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);

但是每当我试图连接到这个 tcp 服务器时

nc localhost 7000 

或者

telnet localhost 7000

连接块没有被执行。

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

我也尝试用小的 iOS 代码连接到这个 tcp 服务器,但没有运气。

知道何时/如何执行此连接块吗?

注意:我是 node.js 的新手并使用 mac os x。

4

1 回答 1

1

首先应该是connection事件。

传递给 createServer 的函数成为“连接”事件的事件处理程序。

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

如果您想收听connection事件,请这样做 -

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

server.addListener("connection", function () {
    console.log("connected");    
});
于 2013-09-10T10:57:18.400 回答