0
0
mirror of https://github.com/nodejs/node.git synced 2024-12-01 16:10:02 +01:00
nodejs/test/pummel/test-tcp-pingpong.js

93 lines
2.3 KiB
JavaScript
Raw Normal View History

require("../common");
net = require("net");
2009-06-18 14:34:49 +02:00
var tests_run = 0;
function pingPongTest (port, host, on_complete) {
var N = 1000;
var count = 0;
var sent_final_ping = false;
var server = net.createServer(function (socket) {
assert.equal(true, socket.remoteAddress !== null);
assert.equal(true, socket.remoteAddress !== undefined);
2009-06-18 14:34:49 +02:00
if (host === "127.0.0.1")
assert.equal(socket.remoteAddress, "127.0.0.1");
2009-06-18 14:34:49 +02:00
else if (host == null)
assert.equal(socket.remoteAddress, "::1");
2009-06-18 14:34:49 +02:00
socket.setEncoding("utf8");
socket.setNoDelay();
2009-06-18 14:34:49 +02: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 14:34:49 +02:00
if (/PING/.exec(data)) {
socket.write("PONG");
2009-06-18 14:34:49 +02:00
}
2009-06-27 20:40:43 +02:00
});
2009-06-18 14:34:49 +02:00
socket.addListener("end", function () {
assert.equal("writeOnly", socket.readyState);
2009-06-18 14:34:49 +02:00
socket.close();
2009-06-27 20:40:43 +02:00
});
2009-06-18 14:34:49 +02:00
socket.addListener("close", function (had_error) {
assert.equal(false, had_error);
assert.equal("closed", socket.readyState);
2009-06-18 14:34:49 +02:00
socket.server.close();
2009-06-27 20:40:43 +02:00
});
2009-06-18 14:34:49 +02:00
});
server.listen(port, host);
var client = net.createConnection(port, host);
client.setEncoding("utf8");
2009-04-22 15:52:23 +02:00
2009-06-29 13:18:30 +02:00
client.addListener("connect", function () {
assert.equal("open", client.readyState);
client.write("PING");
2009-06-27 20:40:43 +02:00
});
client.addListener("data", function (data) {
assert.equal("PONG", data);
2009-08-26 22:03:19 +02: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-27 20:40:43 +02:00
});
2009-06-18 14:34:49 +02:00
client.addListener("close", function () {
assert.equal(N+1, count);
assert.equal(true, sent_final_ping);
2009-06-18 14:34:49 +02:00
if (on_complete) on_complete();
tests_run += 1;
2009-06-27 20:40:43 +02:00
});
2009-06-18 14:34:49 +02:00
}
2009-08-26 18:22:00 +02:00
/* All are run at once, so run on different ports */
2010-02-26 21:06:32 +01:00
pingPongTest(PORT, "localhost");
pingPongTest(PORT+1, null);
2010-03-02 22:10:05 +01: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-02 22:10:05 +01:00
assert.equal(solaris ? 2 : 3, tests_run);
});