ping() and close() for connection

This commit is contained in:
Andrey Sidorov 2012-07-16 19:48:03 +10:00
parent 6d565ec0e9
commit f3681b9aa2
2 changed files with 57 additions and 0 deletions

View file

@ -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)

34
test/connection-utils.js Normal file
View file

@ -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();
});
})
});