2015-05-19 19:00:06 +08:00
|
|
|
'use strict';
|
2016-02-05 08:27:15 +08:00
|
|
|
const common = require('../common');
|
|
|
|
const assert = require('assert');
|
|
|
|
const dgram = require('dgram');
|
2010-06-12 17:40:24 +08:00
|
|
|
|
2010-12-06 03:15:30 +08:00
|
|
|
function pingPongTest(port, host) {
|
2010-06-12 17:40:24 +08:00
|
|
|
|
2016-02-05 08:27:15 +08:00
|
|
|
const server = dgram.createSocket('udp4', common.mustCall((msg, rinfo) => {
|
2018-10-13 01:09:09 +08:00
|
|
|
assert.strictEqual(msg.toString('ascii'), 'PING');
|
2016-02-05 08:27:15 +08:00
|
|
|
server.send('PONG', 0, 4, rinfo.port, rinfo.address);
|
|
|
|
}));
|
2010-06-12 17:40:24 +08:00
|
|
|
|
2010-12-06 03:15:30 +08:00
|
|
|
server.on('error', function(e) {
|
2010-06-12 17:40:24 +08:00
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
|
2010-12-06 03:15:30 +08:00
|
|
|
server.on('listening', function() {
|
2017-04-28 09:06:42 +08:00
|
|
|
console.log(`server listening on ${port}`);
|
2010-06-12 17:40:24 +08:00
|
|
|
|
2016-01-14 04:42:45 +08:00
|
|
|
const client = dgram.createSocket('udp4');
|
2010-06-12 17:40:24 +08:00
|
|
|
|
2016-02-05 08:27:15 +08:00
|
|
|
client.on('message', function(msg) {
|
2018-10-13 01:09:09 +08:00
|
|
|
assert.strictEqual(msg.toString('ascii'), 'PONG');
|
2010-06-12 17:40:24 +08:00
|
|
|
|
2016-02-05 08:27:15 +08:00
|
|
|
client.close();
|
2010-06-12 17:40:24 +08:00
|
|
|
server.close();
|
|
|
|
});
|
|
|
|
|
2010-12-06 03:15:30 +08:00
|
|
|
client.on('error', function(e) {
|
2010-06-12 17:40:24 +08:00
|
|
|
throw e;
|
|
|
|
});
|
|
|
|
|
2017-04-28 09:06:42 +08:00
|
|
|
console.log(`Client sending to ${port}`);
|
2016-02-05 08:27:15 +08:00
|
|
|
|
|
|
|
function clientSend() {
|
|
|
|
client.send('PING', 0, 4, port, 'localhost');
|
|
|
|
}
|
|
|
|
|
|
|
|
clientSend();
|
2010-06-12 17:40:24 +08:00
|
|
|
});
|
2010-07-06 04:38:13 +08:00
|
|
|
server.bind(port, host);
|
2016-02-05 08:27:15 +08:00
|
|
|
return server;
|
2010-06-12 17:40:24 +08:00
|
|
|
}
|
|
|
|
|
2016-02-05 08:27:15 +08:00
|
|
|
const server = pingPongTest(common.PORT, 'localhost');
|
|
|
|
server.on('close', common.mustCall(pingPongTest.bind(undefined, common.PORT)));
|