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

58 lines
1.3 KiB
JavaScript
Raw Normal View History

2010-12-05 07:20:34 +08:00
var common = require('../common');
var assert = require('assert');
2010-12-05 06:45:52 +08:00
2010-12-05 07:20:34 +08:00
var net = require('net');
2010-12-05 06:45:52 +08:00
var N = 50;
var c = 0;
var client_recv_count = 0;
var disconnect_count = 0;
2010-12-05 06:45:52 +08:00
var server = net.createServer(function(socket) {
socket.addListener('connect', function() {
socket.write('hello\r\n');
2009-06-28 02:40:43 +08:00
});
2010-12-05 06:45:52 +08:00
socket.addListener('end', function() {
socket.end();
2009-06-28 02:40:43 +08:00
});
2010-12-05 06:45:52 +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
2010-12-05 06:45:52 +08:00
server.listen(common.PORT, function() {
console.log('listening');
var client = net.createConnection(common.PORT);
2009-08-27 00:22:00 +08:00
2010-12-05 06:45:52 +08:00
client.setEncoding('UTF8');
2009-08-27 00:22:00 +08:00
2010-12-05 06:45:52 +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-12-05 06:45:52 +08:00
client.addListener('data', function(chunk) {
2010-03-10 08:27:49 +08:00
client_recv_count += 1;
2010-12-05 06:45:52 +08:00
console.log('client_recv_count ' + client_recv_count);
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-12-05 06:45:52 +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(common.PORT); // reconnect
2010-03-10 08:27:49 +08:00
else
server.close();
});
2009-08-27 00:22:00 +08:00
});
2010-12-05 06:45:52 +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