Reputation: 25
Trying to create an echo server test with both client and server in the same node process. This code works if I split it into 2 files (server and client) but it does not work if combined into 1 file. How can I get it to work inside 1 file?
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);
});
and same in 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
Upvotes: 1
Views: 167
Reputation: 3838
while (true) {
sock.write("hello\r\n");
}
This is your problem. You're writing to the stream indefinitely; and if it never ends, it won't trigger your "data" event. To illustrate more clearly, try this (in the place of the code above):
while (true) {
console.log("hello!");
sock.write("hello\r\n");
}
Or:
var i = 0;
while (i < 5) {
i++;
sock.write("hello\r\n");
}
EDIT: To keep echoing indefinitely, perhaps try something like this:
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);
Upvotes: 1