尝试在同一节点进程中同时使用客户端和服务器创建echo服务器测试。如果我将它拆分为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
答案 0 :(得分:1)
while (true) {
sock.write("hello\r\n");
}
这是你的问题。你无限期地写到了流;如果它永远不会结束,它将不会触发您的“数据”事件。为了更清楚地说明,试试这个(取代上面的代码):
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);