Compare commits

...

27 Commits

Author SHA1 Message Date
James Coglan 569ec1d62e Perform more stringent checks on request headers so that it should not be possible to get a driver for requests with invalid headers. 2017-10-30 22:53:34 +00:00
James Coglan 8128bec1e0 Bump version to 0.7.0. 2017-09-11 21:48:56 +01:00
James Coglan 7be31c44e6 Use package.json rather than .npmignore to list files in the package. 2017-09-11 21:44:53 +01:00
James Coglan 09476b8ed8 Add an example of using the client driver with the net module. 2017-08-15 19:19:35 +01:00
James Coglan d3396ace77 Extract the license into its own file. 2017-08-15 18:45:36 +01:00
James Coglan 1967d6bbb8 Rename tcp_server.js to net_server.js. 2017-08-08 23:39:08 +01:00
James Coglan 1325828a9e Add ping/pong events to the API. 2017-08-02 21:57:47 +01:00
James Coglan b82b7fa39a Drop testing for io.js releases, which barely anybody is still using. 2017-08-01 23:48:19 +01:00
James Coglan c5c97bb30b Formatting tweaks to package.json. 2017-08-01 00:49:41 +01:00
James Coglan 9a16e7aa27 Drop Node 0.6 support; it's no longer possible to make it work on Travis because installing a working version of npm is impossible since it depends on osenv, which doesn't work on 0.6. 2017-07-30 20:02:37 +01:00
James Coglan ed1ce79915 Install a ^-compatible npm on Node 0.8. 2017-07-30 19:50:30 +01:00
James Coglan a1f70fb7f7 Test on Node 7 and 8. 2017-07-30 19:36:07 +01:00
James Coglan 751c77aa1d Replace the built-in Node HTTP parser with the http-parser-js package. 2017-07-30 19:34:41 +01:00
James Coglan b76f4e27d0 Correct the HTTP parser magic numbers. The numbers we had were correct for Node 0.12 but not for releases since then. 2017-07-30 19:26:45 +01:00
James Coglan c4494ff88a Bump version to 0.6.5. 2016-05-20 08:41:04 +01:00
James Coglan cfb2a86838 Test on Node 6.0. 2016-04-30 13:08:02 +01:00
James Coglan 6a92cacf62 Apply masking to messages once the payload has been placed in the frame buffer rather than mutating the original message. 2016-04-27 22:28:58 +01:00
James Coglan 2be829546b Bump version to 0.6.4. 2016-01-07 08:58:29 +00:00
James Coglan 7f3bb13b5c In draft-75/76, convert all non-string values to strings before sending. 2016-01-06 23:20:47 +00:00
James Coglan ffa0aa3a8f Convert numbers to strings when sending frames.
In draft-75/76, passing a number to text() or frame() results in the
sender allocating a buffer of that size and sending it to the other
peer, leaking random blocks of memory.

In hybi, a call to text(), binary() or ping() with a number will fail,
because the input is expected to be a buffer and so an internal method
call fails.

Both kinds of driver now convert numbers to strings, which is what
browsers do with calls to send().
2016-01-06 23:12:44 +00:00
James Coglan 7c64c35c74 Create CODE_OF_CONDUCT.md. 2015-11-08 12:16:08 +00:00
James Coglan 10481b81db Bump version to 0.6.3. 2015-11-06 22:16:36 +00:00
James Coglan 5b3c8131c4 Test on Node 5. 2015-11-05 21:22:37 +00:00
James Coglan b0b0d69ce4 Throw a more helpful error if a client driver is created with an invalid URL. 2015-10-17 21:44:36 +01:00
James Coglan 3461e0187b Run tests on major versions of iojs and node 4. 2015-10-17 12:58:10 +01:00
James Coglan 5b59d0fcd8 Use the modulo operator rather than Math.floor() to check whether the draft-76 keys are legit. 2015-10-02 21:35:22 +01:00
James Coglan 68990a260b Close the connection if a draft-76 client sends a Sec-WebSocket-Key header where the numeric value is a non-integer multiple of the number of spaces. 2015-10-01 23:47:15 +01:00
21 changed files with 334 additions and 101 deletions
-6
View File
@@ -1,6 +0,0 @@
.git
.gitignore
.npmignore
.travis.yml
node_modules
spec
+7 -3
View File
@@ -1,11 +1,15 @@
sudo: false
language: node_js
node_js:
- "0.6"
- "0.8"
- "0.10"
- "0.12"
- "iojs"
- "4"
- "5"
- "6"
- "7"
- "8"
before_install:
- '[ "${TRAVIS_NODE_VERSION}" = "0.6" ] && npm conf set strict-ssl false || true'
- '[ "${TRAVIS_NODE_VERSION}" = "0.8" ] && npm install -g npm@~1.4.0 || true'
+18
View File
@@ -1,3 +1,21 @@
### 0.7.0 / 2017-09-11
* Add `ping` and `pong` to the set of events users can listen to
* Replace the bindings to Node's HTTP parser with `http-parser-js`
### 0.6.5 / 2016-05-20
* Don't mutate buffers passed in by the application when masking
### 0.6.4 / 2016-01-07
* If a number is given as input for a frame payload, send it as a string
### 0.6.3 / 2015-11-06
* Reject draft-76 handshakes if their Sec-WebSocket-Key headers are invalid
* Throw a more helpful error if a client is created with an invalid URL
### 0.6.2 / 2015-07-18
* When the peer sends a close frame with no error code, emit 1000
+4
View File
@@ -0,0 +1,4 @@
# Code of Conduct
All projects under the [Faye](https://github.com/faye) umbrella are covered by
the [Code of Conduct](https://github.com/faye/code-of-conduct).
+20
View File
@@ -0,0 +1,20 @@
# The MIT License
Copyright (c) 2010-2017 James Coglan
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+11 -24
View File
@@ -281,6 +281,17 @@ describing the error.
Adds a callback to execute when the socket becomes closed. The `event` object
has `code` and `reason` attributes.
#### `driver.on('ping', function(event) {})`
Adds a callback block to execute when a ping is received. You do not need to
handle this by sending a pong frame yourself; the driver handles this for you.
#### `driver.on('pong', function(event) {})`
Adds a callback block to execute when a pong is received. If this was in
response to a ping you sent, you can also handle this event via the
`driver.ping(message, function() { ... })` callback.
#### `driver.addExtension(extension)`
Registers a protocol extension whose operation will be negotiated via the
@@ -357,27 +368,3 @@ Returns the WebSocket version in use as a string. Will either be `hixie-75`,
Returns a string containing the selected subprotocol, if any was agreed upon
using the `Sec-WebSocket-Protocol` mechanism. This value becomes available after
`emit('open')` has fired.
## License
(The MIT License)
Copyright (c) 2010-2015 James Coglan
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+33
View File
@@ -0,0 +1,33 @@
'use strict';
var net = require('net'),
url = require('url'),
websocket = require('..'),
deflate = require('permessage-deflate');
var DEFAULT_PORTS = {'ws:': 80, 'wss:': 443};
var uri = url.parse(process.argv[2]),
port = uri.port || DEFAULT_PORTS[uri.protocol],
conn = net.connect({host: uri.hostname, port: port});
var driver = websocket.client(uri.href);
driver.addExtension(deflate);
driver.on('open', function() {
driver.text('Hello, world');
});
driver.on('message', function(event) {
console.log(['message', event.data]);
});
driver.on('close', function(event) {
console.log(['close', event.code, event.reason]);
conn.end();
});
conn.pipe(driver.io);
driver.io.pipe(conn);
driver.start();
@@ -1,3 +1,5 @@
'use strict';
var net = require('net'),
websocket = require('..'),
deflate = require('permessage-deflate');
+1 -12
View File
@@ -27,19 +27,8 @@ var Driver = {
return Server.http.apply(Server, arguments);
},
isSecureRequest: function(request) {
return Server.isSecureRequest(request);
},
isWebSocket: function(request) {
if (request.method !== 'GET') return false;
var connection = request.headers.connection || '',
upgrade = request.headers.upgrade || '';
return request.method === 'GET' &&
connection.toLowerCase().split(/ *, */).indexOf('upgrade') >= 0 &&
upgrade.toLowerCase() === 'websocket';
return Server.isWebSocket(request);
},
validateOptions: function(options, validKeys) {
+8
View File
@@ -144,4 +144,12 @@ Base.MessageEvent = function(data) {
this.data = data;
};
Base.PingEvent = function(data) {
this.data = data;
};
Base.PongEvent = function(data) {
this.data = data;
};
module.exports = Base;
+8
View File
@@ -20,6 +20,9 @@ var Client = function(_url, options) {
var uri = url.parse(this.url),
auth = uri.auth && new Buffer(uri.auth, 'utf8').toString('base64');
if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0)
throw new Error(this.url + ' is not a valid WebSocket URL');
this._pathname = (uri.pathname || '/') + (uri.search || '');
this._headers.set('Host', uri.host);
@@ -41,6 +44,8 @@ Client.generateKey = function() {
};
var instance = {
VALID_PROTOCOLS: ['ws:', 'wss:'],
proxy: function(origin, options) {
return new Proxy(this, origin, options);
},
@@ -88,6 +93,9 @@ var instance = {
this.statusCode = this._http.statusCode;
this.headers = this._http.headers;
if (this._http.error)
return this._failHandshake(this._http.error.message);
if (this._http.statusCode !== 101)
return this._failHandshake('Unexpected response code: ' + this._http.statusCode);
+2
View File
@@ -83,6 +83,8 @@ var instance = {
if (this.readyState === 0) return this._queue([buffer]);
if (this.readyState > 1) return false;
if (typeof buffer !== 'string') buffer = buffer.toString();
var payload = new Buffer(buffer, 'utf8'),
frame = new Buffer(payload.length + 2);
+22 -9
View File
@@ -49,6 +49,24 @@ var instance = {
},
_handshakeResponse: function() {
var headers = this._request.headers,
key1 = headers['sec-websocket-key1'],
number1 = numberFromKey(key1),
spaces1 = spacesInKey(key1),
key2 = headers['sec-websocket-key2'],
number2 = numberFromKey(key2),
spaces2 = spacesInKey(key2);
if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0) {
this.emit('error', new Error('Client sent invalid Sec-WebSocket-Key headers'));
this.close();
return null;
}
this._keyValues = [number1 / spaces1, number2 / spaces2];
var start = 'HTTP/1.1 101 WebSocket Protocol Handshake',
headers = [start, this._headers.toString(), ''];
@@ -58,16 +76,11 @@ var instance = {
_handshakeSignature: function() {
if (this._body.length < this.BODY_SIZE) return null;
var headers = this._request.headers,
key1 = headers['sec-websocket-key1'],
value1 = numberFromKey(key1) / spacesInKey(key1),
key2 = headers['sec-websocket-key2'],
value2 = numberFromKey(key2) / spacesInKey(key2),
md5 = crypto.createHash('md5'),
buffer = new Buffer(8 + this.BODY_SIZE);
var md5 = crypto.createHash('md5'),
buffer = new Buffer(8 + this.BODY_SIZE);
buffer.writeUInt32BE(value1, 0);
buffer.writeUInt32BE(value2, 4);
buffer.writeUInt32BE(this._keyValues[0], 0);
buffer.writeUInt32BE(this._keyValues[1], 4);
new Buffer(this._body).copy(buffer, 8, 0, this.BODY_SIZE);
md5.update(buffer);
+8 -4
View File
@@ -192,7 +192,8 @@ var instance = {
if (this.readyState <= 0) return this._queue([buffer, type, code]);
if (this.readyState > 2) return false;
if (buffer instanceof Array) buffer = new Buffer(buffer);
if (buffer instanceof Array) buffer = new Buffer(buffer);
if (typeof buffer === 'number') buffer = buffer.toString();
var message = new Message(),
isText = (typeof buffer === 'string'),
@@ -263,11 +264,11 @@ var instance = {
buffer.writeUInt32BE(length % 0x100000000, 6);
}
frame.payload.copy(buffer, offset);
if (frame.masked) {
frame.maskingKey.copy(buffer, header);
Hybi.mask(frame.payload, frame.maskingKey).copy(buffer, offset);
} else {
frame.payload.copy(buffer, offset);
Hybi.mask(buffer, frame.maskingKey, offset);
}
this._write(buffer);
@@ -420,6 +421,7 @@ var instance = {
if (opcode === this.OPCODES.ping) {
this.frame(payload, 'pong');
this.emit('ping', new Base.PingEvent(payload.toString()))
}
if (opcode === this.OPCODES.pong) {
@@ -429,6 +431,8 @@ var instance = {
delete callbacks[message];
if (callback) callback()
this.emit('pong', new Base.PongEvent(payload.toString()))
}
},
+48 -20
View File
@@ -71,6 +71,54 @@ var instance = {
for (var key in instance)
Server.prototype[key] = instance[key];
Server.http = function(request, options) {
options = options || {};
if (options.requireMasking === undefined) options.requireMasking = true;
var klass = this.getDriverClass(request),
url = this.determineUrl(request);
return klass && new klass(request, url, options);
};
Server.isWebSocket = function(request) {
var klass = this.getDriverClass(request);
return !!klass;
};
Server.getDriverClass = function(request) {
var headers = request.headers;
var connection = headers['connection'] || '',
key = headers['sec-websocket-key'],
key1 = headers['sec-websocket-key1'],
key2 = headers['sec-websocket-key2'],
origin = headers['origin'],
upgrade = headers['upgrade'] || '',
version = headers['sec-websocket-version'];
if (request.method !== 'GET' ||
connection.toLowerCase().split(/ *, */).indexOf('upgrade') < 0 ||
upgrade.toLowerCase() !== 'websocket')
return null;
if (typeof version === 'string' || typeof key === 'string')
return (version === '13' && key.length > 0) ? Hybi : null;
if (typeof origin !== 'string' || origin.length === 0)
return null;
if (typeof key1 === 'string' && typeof key2 === 'string')
return Draft76;
return Draft75;
};
Server.determineUrl = function(request) {
var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:';
return scheme + '//' + request.headers.host + request.url;
};
Server.isSecureRequest = function(request) {
if (request.connection && request.connection.authorized !== undefined) return true;
if (request.socket && request.socket.secure) return true;
@@ -85,24 +133,4 @@ Server.isSecureRequest = function(request) {
return false;
};
Server.determineUrl = function(request) {
var scheme = this.isSecureRequest(request) ? 'wss:' : 'ws:';
return scheme + '//' + request.headers.host + request.url;
};
Server.http = function(request, options) {
options = options || {};
if (options.requireMasking === undefined) options.requireMasking = true;
var headers = request.headers,
url = this.determineUrl(request);
if (headers['sec-websocket-version'])
return new Hybi(request, url, options);
else if (headers['sec-websocket-key1'])
return new Draft76(request, url, options);
else
return new Draft75(request, url, options);
};
module.exports = Server;
+48 -14
View File
@@ -1,15 +1,17 @@
'use strict';
var NodeHTTPParser = process.binding('http_parser').HTTPParser,
version = NodeHTTPParser.RESPONSE ? 6 : 4;
var NodeHTTPParser = require('http-parser-js').HTTPParser;
var VERSION = process.version.match(/[0-9]+/g).map(function(n) { return parseInt(n, 10) });
var TYPES = {
request: NodeHTTPParser.REQUEST || 'request',
response: NodeHTTPParser.RESPONSE || 'response'
};
var HttpParser = function(type) {
if (type === 'request')
this._parser = new NodeHTTPParser(NodeHTTPParser.REQUEST || 'request');
else
this._parser = new NodeHTTPParser(NodeHTTPParser.RESPONSE || 'response');
this._type = type;
this._parser = new NodeHTTPParser(TYPES[type]);
this._complete = false;
this.headers = {};
@@ -76,20 +78,52 @@ HttpParser.METHODS = {
13: 'PROPPATCH',
14: 'SEARCH',
15: 'UNLOCK',
16: 'REPORT',
17: 'MKACTIVITY',
18: 'CHECKOUT',
19: 'MERGE',
24: 'PATCH'
16: 'BIND',
17: 'REBIND',
18: 'UNBIND',
19: 'ACL',
20: 'REPORT',
21: 'MKACTIVITY',
22: 'CHECKOUT',
23: 'MERGE',
24: 'M-SEARCH',
25: 'NOTIFY',
26: 'SUBSCRIBE',
27: 'UNSUBSCRIBE',
28: 'PATCH',
29: 'PURGE',
30: 'MKCALENDAR',
31: 'LINK',
32: 'UNLINK'
};
if (VERSION[0] === 0 && VERSION[1] === 12) {
HttpParser.METHODS[16] = 'REPORT';
HttpParser.METHODS[17] = 'MKACTIVITY';
HttpParser.METHODS[18] = 'CHECKOUT';
HttpParser.METHODS[19] = 'MERGE';
HttpParser.METHODS[20] = 'M-SEARCH';
HttpParser.METHODS[21] = 'NOTIFY';
HttpParser.METHODS[22] = 'SUBSCRIBE';
HttpParser.METHODS[23] = 'UNSUBSCRIBE';
HttpParser.METHODS[24] = 'PATCH';
HttpParser.METHODS[25] = 'PURGE';
}
HttpParser.prototype.isComplete = function() {
return this._complete;
};
HttpParser.prototype.parse = function(chunk) {
var offset = (version < 6) ? 1 : 0,
consumed = this._parser.execute(chunk, 0, chunk.length) + offset;
var consumed = this._parser.execute(chunk, 0, chunk.length);
if (typeof consumed !== 'number') {
this.error = consumed;
this._complete = true;
return;
}
if (VERSION[0] === 0 && VERSION[1] < 6) consumed += 1;
if (this._complete)
this.body = (consumed < chunk.length)
+13 -7
View File
@@ -1,21 +1,27 @@
{ "name" : "websocket-driver"
, "description" : "WebSocket protocol handler with pluggable I/O"
, "homepage" : "http://github.com/faye/websocket-driver-node"
, "homepage" : "https://github.com/faye/websocket-driver-node"
, "author" : "James Coglan <jcoglan@gmail.com> (http://jcoglan.com/)"
, "keywords" : ["websocket"]
, "license" : "MIT"
, "version" : "0.6.2"
, "engines" : {"node": ">=0.6.0"}
, "version" : "0.7.0"
, "engines" : { "node": ">=0.8.0" }
, "files" : ["lib"]
, "main" : "./lib/websocket/driver"
, "dependencies" : {"websocket-extensions": ">=0.1.1"}
, "devDependencies" : {"jstest": "", "permessage-deflate": ""}
, "scripts" : {"test": "jstest spec/runner.js"}
, "dependencies" : { "http-parser-js": ">=0.4.0"
, "websocket-extensions": ">=0.1.1"
}
, "devDependencies" : { "jstest": "*"
, "permessage-deflate": "*"
}
, "scripts" : { "test": "jstest spec/runner.js" }
, "repository" : { "type" : "git"
, "url" : "git://github.com/faye/websocket-driver-node.git"
}
, "bugs" : "http://github.com/faye/websocket-driver-node/issues"
, "bugs" : "https://github.com/faye/websocket-driver-node/issues"
}
+12 -2
View File
@@ -109,6 +109,16 @@ test.describe("Client", function() { with(this) {
}})
}})
describe("with an invalid URL", function() { with(this) {
define("url", function() { return "stream.wikimedia.org/rc" })
it("throws an error", function() { with(this) {
var message
try { driver() } catch (e) { message = e.message }
assertEqual( "stream.wikimedia.org/rc is not a valid WebSocket URL", message )
}})
}})
describe("with custom headers", function() { with(this) {
before(function() { with(this) {
driver().setHeader("User-Agent", "Chrome")
@@ -247,8 +257,8 @@ test.describe("Client", function() { with(this) {
it("changes the state to closed", function() { with(this) {
assertEqual( false, open )
assertEqual( "Error during WebSocket handshake: Unexpected response code: 4", error.message )
assertEqual( [1002, "Error during WebSocket handshake: Unexpected response code: 4"], close )
assertEqual( "Error during WebSocket handshake: Parse Error", error.message )
assertEqual( [1002, "Error during WebSocket handshake: Parse Error"], close )
assertEqual( "closed", driver().getState() )
}})
}})
@@ -77,6 +77,11 @@ test.describe("draft-75", function() { with(this) {
assertEqual( [0x00, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20, 0x3d, 0x20, 0xef, 0xa3, 0xbf, 0xff], collector().bytes )
}})
it("converts numbers to strings", function() { with(this) {
driver().frame(50)
assertEqual( [0x00, 0x35, 0x30, 0xff], collector().bytes )
}})
it("returns true", function() { with(this) {
assertEqual( true, driver().frame("lol") )
}})
+32
View File
@@ -34,6 +34,7 @@ test.describe("Draft76", function() { with(this) {
var self = this
this._driver.on('open', function(e) { self.open = true })
this._driver.on('message', function(e) { self.message += e.data })
this._driver.on('error', function(e) { self.error = e })
this._driver.on('close', function(e) { self.close = true })
this._driver.io.pipe(this.collector())
this._driver.io.write(this.body())
@@ -81,6 +82,37 @@ test.describe("Draft76", function() { with(this) {
driver().start()
assertEqual( "hixie-76", driver().version )
}})
describe("with an invalid key header", function() { with(this) {
before(function() { with(this) {
request().headers["sec-websocket-key1"] = "2 L785 8o% s9Sy9@V. 4<1P5"
}})
it("writes a closing frame to the socket", function() { with(this) {
expect(driver().io, "emit").given("data", buffer([0xff, 0x00]))
driver().start()
}})
it("does not trigger the onopen event", function() { with(this) {
driver().start()
assertEqual( false, open )
}})
it("triggers the onerror event", function() { with(this) {
driver().start()
assertEqual( "Client sent invalid Sec-WebSocket-Key headers", error.message )
}})
it("triggers the onclose event", function() { with(this) {
driver().start()
assertEqual( true, close )
}})
it("changes the state to closed", function() { with(this) {
driver().start()
assertEqual( "closed", driver().getState() )
}})
}})
}})
describe("frame", function() { with(this) {
+32
View File
@@ -386,6 +386,17 @@ test.describe("Hybi", function() { with(this) {
assertEqual( [0x8a, 0x04, 0x4f, 0x48, 0x41, 0x49], collector().bytes )
}})
it("triggers the onping event when a ping arrives", function() { with(this) {
var ping, pong
driver().on("ping", function(event) { ping = event })
driver().on("pong", function(event) { pong = event })
driver().parse([0x89, 0x04, 0x4f, 0x48, 0x41, 0x49])
assertEqual( "OHAI", ping.data )
assertEqual( undefined, pong )
}})
describe("when a message listener throws an error", function() { with(this) {
before(function() { with(this) {
this.messages = []
@@ -420,6 +431,11 @@ test.describe("Hybi", function() { with(this) {
assertEqual( [0x82, 0x03, 0x48, 0x65, 0x6c], collector().bytes )
}})
it("converts numbers to strings", function() { with(this) {
driver().frame(50)
assertEqual( [0x81, 0x02, 0x35, 0x30], collector().bytes )
}})
it("encodes multibyte characters correctly", function() { with(this) {
driver().frame("Apple = ")
assertEqual( [0x81, 0x0b, 0x41, 0x70, 0x70, 0x6c, 0x65, 0x20, 0x3d, 0x20, 0xef, 0xa3, 0xbf], collector().bytes )
@@ -452,6 +468,11 @@ test.describe("Hybi", function() { with(this) {
assertEqual( [0x89, 0x09, 0x6d, 0x69, 0x63, 0x20, 0x63, 0x68, 0x65, 0x63, 0x6b], collector().bytes )
}})
it("converts numbers to strings", function() { with(this) {
driver().ping(50)
assertEqual( [0x89, 0x02, 0x35, 0x30], collector().bytes )
}})
it("returns true", function() { with(this) {
assertEqual( true, driver().ping() )
}})
@@ -463,6 +484,17 @@ test.describe("Hybi", function() { with(this) {
assert( reply )
}})
it("triggers the onpong event when a pong arrives", function() { with(this) {
var ping, pong
driver().on("ping", function(event) { ping = event })
driver().on("pong", function(event) { pong = event })
driver().parse([0x8a, 0x02, 72, 105])
assertEqual( undefined, ping )
assertEqual( "Hi", pong.data )
}})
it("does not run the callback on non-matching pong", function() { with(this) {
var reply = null
driver().ping("Hi", function() { reply = true })