node/test/simple/test-net-reconnect.js

56 lines
1.2 KiB
JavaScript
Raw Normal View History

require("../common");
2010-03-10 08:27:49 +08:00
net = require('net');
var N = 50;
var c = 0;
var client_recv_count = 0;
var disconnect_count = 0;
2010-03-10 08:27:49 +08:00
var server = net.createServer(function (socket) {
2009-08-27 00:22:00 +08:00
socket.addListener("connect", function () {
socket.write("hello\r\n");
2009-06-28 02:40:43 +08:00
});
socket.addListener("end", function () {
socket.end();
2009-06-28 02:40:43 +08:00
});
2009-08-27 00:22:00 +08:00
socket.addListener("close", function (had_error) {
//console.log("server had_error: " + JSON.stringify(had_error));
assert.equal(false, had_error);
2009-06-28 02:40:43 +08:00
});
2009-08-27 00:22:00 +08:00
});
2010-03-10 08:27:49 +08:00
server.listen(PORT, function () {
console.log('listening');
2010-03-10 08:27:49 +08:00
var client = net.createConnection(PORT);
2009-08-27 00:22:00 +08:00
2010-03-10 08:27:49 +08:00
client.setEncoding("UTF8");
2009-08-27 00:22:00 +08:00
2010-03-10 08:27:49 +08:00
client.addListener("connect", function () {
console.log("client connected.");
2010-03-10 08:27:49 +08:00
});
2009-08-27 00:22:00 +08:00
2010-03-10 08:27:49 +08:00
client.addListener("data", function (chunk) {
client_recv_count += 1;
console.log("client_recv_count " + client_recv_count);
2010-03-10 08:27:49 +08:00
assert.equal("hello\r\n", chunk);
client.end();
2010-03-10 08:27:49 +08:00
});
2009-08-27 00:22:00 +08:00
2010-03-10 08:27:49 +08:00
client.addListener("close", function (had_error) {
console.log("disconnect");
2010-03-10 08:27:49 +08:00
assert.equal(false, had_error);
if (disconnect_count++ < N)
client.connect(PORT); // reconnect
else
server.close();
});
2009-08-27 00:22:00 +08:00
});
process.addListener("exit", function () {
assert.equal(N+1, disconnect_count);
assert.equal(N+1, client_recv_count);
});
2010-03-10 08:27:49 +08:00