node/test/pummel/test-tcp-pingpong.js

93 lines
2.3 KiB
JavaScript
Raw Normal View History

2010-02-25 14:36:17 +08:00
process.mixin(require("../common"));
tcp = require("tcp");
2009-06-18 20:34:49 +08:00
var tests_run = 0;
function pingPongTest (port, host, on_complete) {
var N = 1000;
var count = 0;
var sent_final_ping = false;
2009-09-28 22:08:09 +08:00
var server = tcp.createServer(function (socket) {
assert.equal(true, socket.remoteAddress !== null);
assert.equal(true, socket.remoteAddress !== undefined);
2009-06-18 20:34:49 +08:00
if (host === "127.0.0.1")
assert.equal(socket.remoteAddress, "127.0.0.1");
2009-06-18 20:34:49 +08:00
else if (host == null)
assert.equal(socket.remoteAddress, "127.0.0.1");
2009-06-18 20:34:49 +08:00
socket.setEncoding("utf8");
socket.setNoDelay();
2009-06-18 20:34:49 +08:00
socket.timeout = 0;
socket.addListener("data", function (data) {
puts("server got: " + JSON.stringify(data));
assert.equal("open", socket.readyState);
assert.equal(true, count <= N);
2009-06-18 20:34:49 +08:00
if (/PING/.exec(data)) {
socket.write("PONG");
2009-06-18 20:34:49 +08:00
}
2009-06-28 02:40:43 +08:00
});
2009-06-18 20:34:49 +08:00
socket.addListener("end", function () {
assert.equal("writeOnly", socket.readyState);
2009-06-18 20:34:49 +08:00
socket.close();
2009-06-28 02:40:43 +08:00
});
2009-06-18 20:34:49 +08:00
socket.addListener("close", function (had_error) {
assert.equal(false, had_error);
assert.equal("closed", socket.readyState);
2009-06-18 20:34:49 +08:00
socket.server.close();
2009-06-28 02:40:43 +08:00
});
2009-06-18 20:34:49 +08:00
});
server.listen(port, host);
2009-09-28 22:08:09 +08:00
var client = tcp.createConnection(port, host);
client.setEncoding("utf8");
2009-04-22 21:52:23 +08:00
2009-06-29 19:18:30 +08:00
client.addListener("connect", function () {
assert.equal("open", client.readyState);
client.write("PING");
2009-06-28 02:40:43 +08:00
});
client.addListener("data", function (data) {
assert.equal("PONG", data);
2009-08-27 04:03:19 +08:00
count += 1;
if (sent_final_ping) {
assert.equal("readOnly", client.readyState);
return;
} else {
assert.equal("open", client.readyState);
}
if (count < N) {
client.write("PING");
} else {
sent_final_ping = true;
client.write("PING");
client.close();
}
2009-06-28 02:40:43 +08:00
});
2009-06-18 20:34:49 +08:00
client.addListener("close", function () {
assert.equal(N+1, count);
assert.equal(true, sent_final_ping);
2009-06-18 20:34:49 +08:00
if (on_complete) on_complete();
tests_run += 1;
2009-06-28 02:40:43 +08:00
});
2009-06-18 20:34:49 +08:00
}
2009-08-27 00:22:00 +08:00
/* All are run at once, so run on different ports */
2010-02-27 04:06:32 +08:00
pingPongTest(PORT, "localhost");
pingPongTest(PORT+1, null);
2010-03-03 05:10:05 +08:00
// This IPv6 isn't working on Solaris
var solaris = /sunos/i.test(process.platform);
if (!solaris) pingPongTest(PORT+2, "::1");
process.addListener("exit", function () {
2010-03-03 05:10:05 +08:00
assert.equal(solaris ? 2 : 3, tests_run);
});