From f3681b9aa23445759cfce753be59b26a6271c962 Mon Sep 17 00:00:00 2001 From: Andrey Sidorov Date: Mon, 16 Jul 2012 19:48:03 +1000 Subject: [PATCH] ping() and close() for connection --- lib/x11/xcore.js | 23 +++++++++++++++++++++++ test/connection-utils.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 test/connection-utils.js diff --git a/lib/x11/xcore.js b/lib/x11/xcore.js index 6fcafcf..28cd9a6 100644 --- a/lib/x11/xcore.js +++ b/lib/x11/xcore.js @@ -74,6 +74,7 @@ function XClient(stream, displayNum, screenNum) this.importRequestsFromTemplates(this, coreRequests); this.startHandshake(); + this._closing = false; } util.inherits(XClient, EventEmitter); @@ -83,6 +84,25 @@ XClient.prototype.terminate = function() this.stream.end(); } +// GetAtomName used as cheapest non-modifying request with reply +// 3 - id for shortest standard atom, "ARC" +XClient.prototype.ping = function(cb) { + this.GetAtomName(3, function(err, str) { + if (err) return cb(err); + return cb(); + }); +} + +XClient.prototype.close = function(cb) { + var cli = this; + cli.ping(function(err) { + if (err) return cb(err); + cli.terminate(); + if (cb) cb(); + }); + cli._closing = true; +} + XClient.prototype.importRequestsFromTemplates = function(target, reqs) { var client = this; @@ -93,6 +113,9 @@ XClient.prototype.importRequestsFromTemplates = function(target, reqs) var reqFunc = function req_proxy() { + if (client._closing) + throw new Error('client is in closing state'); + // simple overflow handling (this means that currently there is no way to have more than 65535 requests in the queue // TODO: edge cases testing if (client.seq_num == 65535) diff --git a/test/connection-utils.js b/test/connection-utils.js new file mode 100644 index 0000000..41863b5 --- /dev/null +++ b/test/connection-utils.js @@ -0,0 +1,34 @@ +var x11 = require('../lib/x11'); +var should = require('should'); +var assert = require('assert'); + +describe('Client', function() { + + var display; + beforeEach(function(done) { + var client = x11.createClient(function(dpy) { + display=dpy; + done(); + client.removeListener('error', done); + }); + client.on('error', done); + }); + + it('should respond to ping()', function(done) { + display.client.ping(done); + }); + + it('should allow to enqueue requests and gracefully execute them before close()', function(done) { + var count = 0; + var pong = function(err) { if (err) return done(err); count++; } + display.client.ping(pong); + display.client.ping(pong); + display.client.ping(pong); + display.client.ping(pong); + display.client.close(function(err) { + if (err) return done(err); + assert.equal(count,4); + done(); + }); + }) +});