同一nodejs进程中的客户端和服务器

client and server in same nodejs process

正在尝试在同一节点进程中使用客户端和服务器创建回显服务器测试。如果将此代码拆分为 2 个文件(服务器和客户端),则此代码有效,但如果合并为 1 个文件,则此代码无效。我怎样才能让它在 1 个文件中工作?

var HOST, createServer, g, net;

net = require("net");

HOST = "127.0.0.1";

createServer = function(port) {
  net.createServer(function(sock) {
    sock.write("welcome!  on port " + port + "\r\n");
    console.log("CONNECTED: " + sock.remoteAddress + ":" + sock.remotePort);
    while (true) {
      sock.write("hello\r\n");
    }
  }).listen(port, HOST);
  console.log("server listening on " + port);
};

createServer(7001);

g = net.createConnection(7001, HOST);

g.on("data", function(data) {
  console.log("got " + data);
});

在 coffeescript 中也是如此:

net = require "net"
HOST = "127.0.0.1"

createServer = (port) ->
  net.createServer((sock) ->
    sock.write("welcome!  on port #{port}\r\n")
    console.log("CONNECTED: #{sock.remoteAddress}:#{sock.remotePort}")
    while true # this is the work queue, what ports to send to...                
      sock.write "hello\r\n"
    return
  ).listen port, HOST
  console.log "server listening on #{port}"
  return

createServer(7001)

# XXX why does g.on "data" never fire?                                           
# this works fine if I move it into                                              
# it's own file, how to co-exist                                                 
# this client with server above                                                  
# in same file?                                                                  
g = net.createConnection(7001, HOST)
g.on "data", (data) ->
  console.log "got #{data}"
  return
while (true) {
  sock.write("hello\r\n");
}

这是你的问题。您正在无限期地写入流;如果它永远不会结束,它就不会触发您的 "data" 事件。为了更清楚地说明,试试这个(代替上面的代码):

while (true) {
  console.log("hello!");
  sock.write("hello\r\n");
}

或者:

var i = 0;
while (i < 5) {
  i++;
  sock.write("hello\r\n");
}

编辑: 要无限期地回显,也许可以尝试这样的事情:

net.createServer(function(sock) { 
  sock.write("welcome!  on port " + port + "\r\n");
  console.log("CONNECTED: " + sock.remoteAddress + ":" + sock.remotePort);
  setInterval(function() {
    sock.write("hello\r\n");
  }, 2000);
}).listen(port, HOST);