Skip to content

Commit

Permalink
init
Browse files Browse the repository at this point in the history
  • Loading branch information
ericz committed Jul 2, 2012
1 parent 41084f1 commit 7034fc1
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 184 deletions.
160 changes: 1 addition & 159 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,159 +1 @@
[![Build Status](https://secure.travis-ci.org/einaros/ws.png)](http://travis-ci.org/einaros/ws)

# ws: a node.js websocket library #

`ws` is a simple to use websocket implementation, up-to-date against RFC-6455, and [probably the fastest WebSocket library for node.js](http://hobbycoding.posterous.com/the-fastest-websocket-module-for-nodejs).

Passes the quite extensible Autobahn test suite. See http://einaros.github.com/ws for the full reports.

Comes with a command line utility, `wscat`, which can either act as a server (--listen), or client (--connect); Use it to debug simple websocket services.

## Protocol support ##

* **Hixie draft 76** (Old and deprecated, but still in use by Safari and Opera. Added to ws version 0.4.2, but server only. Can be disabled by setting the `disableHixie` option to true.)
* **HyBi drafts 07-12** (Use the option `protocolVersion: 8`, or argument `-p 8` for wscat)
* **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`, or argument `-p 13` for wscat)

_See the echo.websocket.org example below for how to use the `protocolVersion` option._

## Usage ##

### Installing ###

`npm install ws`

### Sending and receiving text data ###

```js
var WebSocket = require('ws');
var ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function() {
ws.send('something');
});
ws.on('message', function(data, flags) {
// flags.binary will be set if a binary data is received
// flags.masked will be set if the data was masked
});
```

### Sending binary data ###

```js
var WebSocket = require('ws');
var ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function() {
var array = new Float32Array(5);
for (var i = 0; i < array.length; ++i) array[i] = i / 2;
ws.send(array, {binary: true, mask: true});
});
```

Setting `mask`, as done for the send options above, will cause the data to be masked according to the websocket protocol. The same option applies for text data.

### Server example ###

```js
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
});
ws.send('something');
});
```

### Error handling best practices ###

```js
// If the WebSocket is closed before the following send is attempted
ws.send('something');

// Errors (both immediate and async write errors) can be detected in an optional callback.
// The callback is also the only way of being notified that data has actually been sent.
ws.send('something', function(error) {
// if error is null, the send has been completed,
// otherwise the error object will indicate what failed.
});

// Immediate errors can also be handled with try/catch-blocks, but **note**
// that since sends are inherently asynchronous, socket write failures will *not*
// be captured when this technique is used.
try {
ws.send('something');
}
catch (e) {
// handle error
}
```

### echo.websocket.org demo ###

```js
var WebSocket = require('ws');
var ws = new WebSocket('ws://echo.websocket.org/', {protocolVersion: 8, origin: 'http://websocket.org'});
ws.on('open', function() {
console.log('connected');
ws.send(Date.now().toString(), {mask: true});
});
ws.on('close', function() {
console.log('disconnected');
});
ws.on('message', function(data, flags) {
console.log('Roundtrip time: ' + (Date.now() - parseInt(data)) + 'ms', flags);
setTimeout(function() {
ws.send(Date.now().toString(), {mask: true});
}, 500);
});
```

### wscat against echo.websocket.org ###

$ npm install -g ws
$ wscat -c ws://echo.websocket.org -p 8
connected (press CTRL+C to quit)
> hi there
< hi there
> are you a happy parrot?
< are you a happy parrot?

### Other examples ###

For a full example with a browser client communicating with a ws server, see the examples folder.

Note that the usage together with Express 3.0 is quite different from Express 2.x. The difference is expressed in the two different serverstats-examples.

Otherwise, see the test cases.

### Running the tests ###

`make test`

## API Docs ##

See the doc/ directory for Node.js-like docs for the ws classes.

## License ##

(The MIT License)

Copyright (c) 2011 Einar Otto Stangvik &lt;einaros@gmail.com&gt;

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.
Fork of `ws` for better streaming
4 changes: 2 additions & 2 deletions lib/Sender.hixie.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ Sender.prototype.send = function(data, options, cb) {
else this.continuationFrame = true;

try {
this.socket.write(buffer, 'binary', cb);
return this.socket.write(buffer, 'binary', cb);
} catch (e) {
this.error(e.toString());
}
Expand All @@ -75,7 +75,7 @@ Sender.prototype.close = function(code, data, mask, cb) {
this.isClosed = true;
try {
if (this.continuationFrame) this.socket.write(new Buffer([0xff], 'binary'));
this.socket.write(new Buffer([0xff, 0x00]), 'binary', cb);
return this.socket.write(new Buffer([0xff, 0x00]), 'binary', cb);
} catch (e) {
this.error(e.toString());
}
Expand Down
22 changes: 12 additions & 10 deletions lib/Sender.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ Sender.prototype.close = function(code, data, mask) {
var dataBuffer = new Buffer(2 + (data ? Buffer.byteLength(data) : 0));
writeUInt16BE.call(dataBuffer, code, 0);
if (dataBuffer.length > 2) dataBuffer.write(data, 2);
this.frameAndSend(0x8, dataBuffer, true, mask);
return this.frameAndSend(0x8, dataBuffer, true, mask);
}

/**
Expand All @@ -51,7 +51,7 @@ Sender.prototype.close = function(code, data, mask) {

Sender.prototype.ping = function(data, options) {
var mask = options && options.mask;
this.frameAndSend(0x9, data || '', true, mask);
return this.frameAndSend(0x9, data || '', true, mask);
}

/**
Expand All @@ -62,7 +62,7 @@ Sender.prototype.ping = function(data, options) {

Sender.prototype.pong = function(data, options) {
var mask = options && options.mask;
this.frameAndSend(0xa, data || '', true, mask);
return this.frameAndSend(0xa, data || '', true, mask);
}

/**
Expand All @@ -78,7 +78,7 @@ Sender.prototype.send = function(data, options, cb) {
if (this.firstFragment === false) opcode = 0;
else this.firstFragment = false;
if (finalFragment) this.firstFragment = true
this.frameAndSend(opcode, data, finalFragment, mask, cb);
return this.frameAndSend(opcode, data, finalFragment, mask, cb);
}

/**
Expand All @@ -89,16 +89,17 @@ Sender.prototype.send = function(data, options, cb) {

Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData, cb) {
var canModifyData = false;
var out = null;

if (!data) {
try {
this._socket.write(new Buffer([opcode | (finalFragment ? 0x80 : 0), 0 | (maskData ? 0x80 : 0)].concat(maskData ? [0, 0, 0, 0] : [])), 'binary', cb);
out = this._socket.write(new Buffer([opcode | (finalFragment ? 0x80 : 0), 0 | (maskData ? 0x80 : 0)].concat(maskData ? [0, 0, 0, 0] : [])), 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
else this.emit('error', e);
}
return;
return out;
}

if (!Buffer.isBuffer(data)) {
Expand Down Expand Up @@ -143,7 +144,7 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
if (mergeBuffers) {
bufferUtil.mask(data, mask, outputBuffer, dataOffset, dataLength);
try {
this._socket.write(outputBuffer, 'binary', cb);
out = this._socket.write(outputBuffer, 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
Expand All @@ -154,7 +155,7 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
bufferUtil.mask(data, mask, data, 0, dataLength);
try {
this._socket.write(outputBuffer, 'binary');
this._socket.write(data, 'binary', cb);
out = this._socket.write(data, 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
Expand All @@ -167,7 +168,7 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
if (mergeBuffers) {
data.copy(outputBuffer, dataOffset);
try {
this._socket.write(outputBuffer, 'binary', cb);
out = this._socket.write(outputBuffer, 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
Expand All @@ -177,14 +178,15 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
else {
try {
this._socket.write(outputBuffer, 'binary');
this._socket.write(data, 'binary', cb);
out = this._socket.write(data, 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
else this.emit('error', e);
}
}
}
return out;
}

module.exports = Sender;
Expand Down
2 changes: 1 addition & 1 deletion lib/WebSocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ WebSocket.prototype.send = function(data, options, cb) {
if (typeof cb == 'function') cb(error);
});
}
else this._sender.send(data, options, cb);
else return this._sender.send(data, options, cb);
}

/**
Expand Down
18 changes: 6 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
{
"author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
"name": "ws",
"description": "simple to use, blazing fast and thoroughly tested websocket client, server and console for node.js, up-to-date against RFC-6455",
"version": "0.4.19",
"author": "Eric Zhang",
"name": "binaryws",
"description": "Streaming optimized version of `ws`",
"version": "0.0.0",
"repository": {
"type": "git",
"url": "git://github.com/einaros/ws.git"
},
"bin": {
"wscat": "./bin/wscat"
"url": "git://github.com/binaryjs/binaryws.git"
},
"scripts": {
"test": "make test",
"install": "node install.js"
},
"engines": {
"node": ">=0.4.0"
},
"config": {
"verbose" : false
"node": ">=0.6.0"
},
"dependencies": {
"commander": "~0.6.1",
Expand Down

1 comment on commit 7034fc1

@max-mapper
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should pull req this!

Please sign in to comment.