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

91 lines
2.2 KiB
JavaScript
Raw Normal View History

process.mixin(require("./common"));
tcp = require("tcp");
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;
2009-09-28 16:08:09 +02:00
var server = tcp.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, "127.0.0.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.send("PONG");
}
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);
2009-09-28 16:08:09 +02:00
var client = tcp.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.send("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.send("PING");
} else {
sent_final_ping = true;
client.send("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 */
pingPongTest(20989, "localhost");
pingPongTest(20988, null);
pingPongTest(20997, "::1");
process.addListener("exit", function () {
assert.equal(3, tests_run);
});