spilt script out

This commit is contained in:
sstent
2012-06-22 14:34:45 -04:00
parent 76ec83b869
commit e2c1f5fe1b
42 changed files with 112652 additions and 112963 deletions

View File

@@ -11,6 +11,7 @@
<script src="/static/form2js/form2js.js"></script>
<script src="/static/form2js/jquery.toObject.js"></script>
<script src="/static/form2js/json2.js"></script>
<script src="/static/javascripts/script.js"></script>
<link rel="stylesheet" href="/static/stylesheets/smoothness/jquery-ui-1.8.20.custom.css"/>
<link rel="stylesheet" href="/static/stylesheets/jui_style.css"/>
<link rel="stylesheet" href="/static/stylesheets/style.css"/>
@@ -35,318 +36,6 @@
</div>
</script>
<script type='text/javascript'>
$(document).ready(function() {
var socket = io.connect();
exercise_autocompletedata = "unset";
bike_autocompletedata = "unset";
socket.emit('getactivites', 'please');
socket.emit('getexercises', 'please');
socket.emit('getexpresso', 'please');
socket.on('populateactivities', function(json) {
console.log('#poulate recieved');
var content = "";
$(".workoutdata").hide();
$('#ActivityList').empty();
$( "#ActivityList" ).html(
$( "#movieTemplate1" ).render( json )
);
$(".ui-accordion-content").css("display", "block");
$("#ActivityList").accordion('destroy').accordion({
header: 'h3',
active: false,
collapsible: true
});
});
//poulate activity by id
socket.on('populateactivitybyid', function(json) {
//set document id
$('span.ActivityID').attr('docid',json._id);
//poulate name
$('input[name="Activities.Activity.name"]').attr('value', json.Activities.Activity.name)
//poulate date
$('input[name="Activities.Activity.date"]').attr('value', json.Activities.Activity.date)
// Activities.Activity.date
// for each lap
if ("Lap" in json.Activities.Activity) {
var array = json.Activities.Activity.Lap;
$.each(array, function(index, value) {
////if run
if ("run" in value) { AddPopulatedLap("Run", value.run.name, value.run.time, value.run.distance, "", "" , "")};
////if bike
if ("bike" in value) { AddPopulatedLap("Bike", value.bike.name, value.bike.time, value.bike.distance, "", "" , "")};
////if cardio
if ("cardio" in value) { AddPopulatedLap("Cardio", value.cardio.name, value.cardio.time, value.cardio.distance, "", "" , "")};
////if exercise
if ("exercise" in value) { AddPopulatedLap("Exercise", value.exercise.name, "", "", value.exercise.sets, value.exercise.reps , value.exercise.weight)};
////if rest
if ("rest" in value) { AddPopulatedLap("Rest", "", "", "", "", "" , "")};
});
};
$('#savecopy').attr('style', 'display: block');
///refresh tabvle
$('#sortable').trigger('sortupdate');
//switch to tab
$( "#tabs" ).tabs( "select" , 1 )
});
function AddPopulatedLap(type, name, time, distance, set, reps, weight) {
console.log('type= ' + type);
var newElem = $('.new-lap').clone(true).attr('style', 'display: block');
$(newElem).removeClass('new-lap');
$(newElem).appendTo('#sortable');
$(newElem).children('.laptype').val(type).trigger('change');
$(newElem).children('input').attr('disabled',false);
$(newElem).find('.lapname').attr('value', name);
$(newElem).find('.lapdistance').attr('value', distance);
$(newElem).find('.laptime').attr('value', time);
$(newElem).sortable( "refresh" );
};
//var addtype = $(this).attr('value');
//var newElem = $('.new-' + addtype).clone(true).attr('style', 'display: block');
//$(newElem).removeClass("new-" + addtype);
//$(newElem).children('input').attr('disabled',false);
//$(newElem).appendTo('#sortable');
//$(newElem).sortable( "refresh" );
//$('#sortable').trigger('sortupdate');
////populate exercise sortable
socket.on('populateexercises', function(json) {
//console.log('#exercises recieved' + JSON.stringify(json, null, ' '));
var content = "";
$('ul#sortableexercises li').remove();
$('span.ExerciseID').attr('docid',json[0]._id);
//$( "ul#sortableexercises" ).append('<li style="display: none"><input type="text" name="_id" value="'+ json[0]._id + '"></li>')
///// for loop
var array = json[0].exercise.name;
exercise_autocompletedata = array;
$('#sortable').trigger('sortupdate');
$.each(array, function(index, value) {
$( "ul#sortableexercises" ).append('<li class=ui-state-default><input type="text" name="exercise.name[]" value="'+ value + '"></li>')
});
////populate expresso sortable
socket.on('populateexpresso', function(json) {
//console.log('#tracks recieved' + JSON.stringify(json, null, ' '));
var content = "";
$('ul#sortableexpresso li').remove();
$('span.ExpressoID').attr('docid',json[0]._id);
var barray = json[0].track.name;
bike_autocompletedata = barray;
$('#sortable').trigger('sortupdate');
$.each(barray, function(index, value) {
$( "ul#sortableexpresso" ).append('<li class=ui-state-default><input type="text" name="track.name[]" value="'+ value + '"></li>')
});
});
});
//THe TABs stuff
$( "#tabs" ).tabs();
$( "#tabs" ).tabs('select' , 0);
//sets buttons to be jquery buttons
$("button").button();
//sets datepickers
$( "#datepicker" ).datepicker();
$( "#tabs" ).bind( "tabsselect", function(event, ui) {
if (ui.index == 0) {
console.log('send stuff ' + ui.index );
socket.emit('getactivites', 'please');
};
if (ui.index == 2) {
console.log('send stuff ' + ui.index );
socket.emit('getexercises', 'please');
};
if (ui.index == 3) {
console.log('send stuff ' + ui.index );
socket.emit('getexpresso', 'please');
};
});
$('#ActivityList').delegate('a.activitydelete', 'click', function() {
socket.emit('delactivity', $(this).attr('title'));
return false;
});
$('#ActivityList').delegate('a.activityedit', 'click', function() {
socket.emit('getactivitybyid', $(this).attr('title'));
return false;
});
//THe Sortable Stuff
$("#sortable").sortable({
placeholder: "ui-state-highlight",
revert: true,
stop: function(event, ui) {
$('#sortable').trigger('sortupdate')
},
});
$("#sortable").bind('sortupdate', function(event, ui) {
$('#sortable li').each(function(){
var itemindex= $(this).index()
$(this).children('label.uiindex').html('Lap '+ itemindex );
$(this).find('input').each(function(){
var newname = $(this).attr('name').replace(/\[[0-9]*\]/,'[' + itemindex + ']');
//console.log('newname' + newname );
$(this).attr("name",newname);
});
$(this).find('input.exertags').autocomplete({source: exercise_autocompletedata});
//select: function(event, ui) { ... }
//$(this).find('input.biketags').autocomplete({source: bike_autocompletedata})
//console.log('exercise_autocompletedata' + JSON.stringify(exercise_autocompletedata, null, ' ') );
//console.log('bike_autocompletedata' + JSON.stringify(bike_autocompletedata, null, ' ') );
});
});
$("#sortableexercises").sortable({
placeholder: "ui-state-highlight",
revert: true,
});
$('ul').on('click', '.delete',function() {
$(this).closest('li').remove();
$('#sortable').trigger('sortupdate')
});
///All the Buttons
$("button").button();
//adds selectable element
$("button").click(function() {
var addtype = $(this).attr('value');
var newElem = $('.new-' + addtype).clone(true).attr('style', 'display: block');
$(newElem).removeClass("new-" + addtype);
$(newElem).children('input').attr('disabled',false);
$(newElem).appendTo('#sortable');
$(newElem).sortable( "refresh" );
$('#sortable').trigger('sortupdate');
});
$("button.AddExercise").click(function() {
$( "ul#sortableexercises" ).append('<li class=ui-state-default><input type="text" name="exercise.name[]" hint="Name" placeholder="Exercise Name"></li>')
});
$("button.AddExpresso").click(function() {
$( "ul#sortableexpresso" ).append('<li class=ui-state-default><input type="text" name="track.name[]" hint="Name" placeholder="Track Name"><input type="text" name="track.distance[]" hint="Name" placeholder="Distance"><input type="text" name="track.peak[]" hint="Name" placeholder="Peak"></li>')
});
$('#Activity').find('input.datepicker').datepicker();
$('#Activity').find('input.datepicker').datepicker('setDate', new Date());
$('#save').click(function() {
var docid =$(this).closest('span').attr('docid');
var selector= "#myForm"
var formDataAll = $(selector).toObject({mode: 'all'});
socket.emit('addactivity', formDataAll[0], docid);
//console.log('All ', JSON.stringify(formDataAll[0], null, ' '));
$('ul#sortable li').remove('.removable');
$('#Activity').find('input').attr('value','');
$('span.ActivityID').removeAttr('docid');
$('#savecopy').attr('style', 'display: none');
$( "#tabs" ).tabs( "select" , 0 )
$('#Activity').find('input.datepicker').datepicker();
$('#Activity').find('input.datepicker').datepicker('setDate', new Date());
return false;
});
$('#savecopy').click(function() {
var selector= "#myForm"
var formDataAll = $(selector).toObject({mode: 'all'});
socket.emit('addactivity', formDataAll[0]);
//console.log('All ', JSON.stringify(formDataAll[0], null, ' '));
$('ul#sortable li').remove('.removable');
$('#Activity').find('input').attr('value','');
$('span.ActivityID').removeAttr('docid');
$('#savecopy').attr('style', 'display: none');
$( "#tabs" ).tabs( "select" , 0 )
$('#Activity').find('input.datepicker').datepicker();
$('#Activity').find('input.datepicker').datepicker('setDate', new Date());
return false;
});
$('#saveexercises').click(function() {
var docid =$(this).closest('span').attr('docid');
var selector= "#ExerciseForm"
var formDataAll = $(selector).toObject({mode: 'all'});
socket.emit('updateexercises', formDataAll[0], docid);
//console.log('All ', JSON.stringify(formDataAll, null, ' '));
// to prevent the page from changing
$('ul#sortableexercises li').remove();
$( "#tabs" ).tabs( "select" , 0 )
return false;
});
$('#saveexpresso').click(function() {
var docid =$(this).closest('span').attr('docid');
var selector= "#ExpressoForm"
var formDataAll = $(selector).toObject({mode: 'all'});
socket.emit('updateexpresso', formDataAll[0], docid);
console.log('All ', JSON.stringify(formDataAll, null, ' '));
// to prevent the page from changing
$('ul#sortableexpresso li').remove();
$( "#tabs" ).tabs( "select" , 0 )
return false;
});
$('#cancelform').click(function() {
$('ul#sortable li').remove('.removable');
$('#Activity').find('input').attr('value','');
$('#Activity').find('input.datepicker').datepicker();
$('#Activity').find('input.datepicker').datepicker('setDate', new Date());
return false;
});
$('#my-text-link').click(function() { // bind click event to link
$tabs.tabs('select', 2); // switch to third tab
return false;
});
$('ul').on('change', '.laptype',function() {
console.log ('value= ' + $(this).val() );
switch($(this).val()) {
case "Run":
$(this).siblings('span').html('<input type="text" class="lapname" name="Activities.Activity.Lap[0].run.name" placeholder="Location"><input type="text" class="lapdistance" name="Activities.Activity.Lap[0].run.distance" placeholder="distance"><input type="text" class="laptime" name="Activities.Activity.Lap[0].run.time" placeholder="hh:mm:ss"><a href=# class=delete>delete</a>');
break;
case "Bike":
$(this).siblings('span').html('<input type="text" class="lapname biketags" name="Activities.Activity.Lap[0].bike.name" hint="Name" placeholder="Track Name"><input type="text" class="lapdistance" name="Activities.Activity.Lap[0].bike.distance" placeholder="Distance"> <input type="text" class="laptime" name="Activities.Activity.Lap[0].bike.time" placeholder="hh:mm:ss"><a href=# class=delete>delete</a>');
break;
case "Cardio":
$(this).siblings('span').html('<input type="text" class="lapname" name="Activities.Activity.Lap[0].cardio.name" placeholder="Machine"><input type="text" class="lapdistance" name="Activities.Activity.Lap[0].cardio.distance" placeholder="Distance"><input type="text" class="laptime" name="Activities.Activity.Lap[0].cardio.time" placeholder="hh:mm:ss"><a href=# class=delete>delete</a>');
break;
case "Exercise":
$(this).siblings('span').html('<input type="text" class="lapname exertags" name="Activities.Activity.Lap[0].exercise.name" placeholder="Exercise Name"><input type="text" name="Activities.Activity.Lap[0].exercise.sets" placeholder="Sets"><input type="text" name="Activities.Activity.Lap[0].exercise.sets" placeholder="Reps"><a href=# class=delete>delete</a>');
break;
case "Rest":
$(this).siblings('span').html('<input type="text" class="lapname" name="Activities.Activity.Lap[0].rest[0]" placeholder="Rest"><a href=# class=delete>delete</a>');
break;
};
$('#sortable').trigger('sortupdate')
});
});
</script>
</head>
<body>
<div id="container">

View File

@@ -45,11 +45,8 @@
"node": "*"
},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "a1b994eb7a760beadecf3b57f1d693902c92e5a8"
},
"_from": "policyfile@0.0.4"
}

View File

@@ -57,11 +57,8 @@
"node": "*"
},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "f583ce9d7991094cc7ccb1618bec1533d009841a"
},
"_from": "redis@0.6.7"
}

View File

@@ -20,11 +20,8 @@
"_id": "zeparser@0.0.5",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "7e653297721a1f654b5727a2b2db0f778ff552c5"
},
"_from": "zeparser@0.0.5"
}

View File

@@ -26,11 +26,8 @@
"optionalDependencies": {},
"_id": "active-x-obfuscator@0.0.1",
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "eb70ab277e24cac53aea004cf8a14bebb7f8d76e"
},
"_from": "active-x-obfuscator@0.0.1"
}

View File

@@ -23,11 +23,8 @@
"node": "*"
},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "ae85ec69785f869027bc590d72224e6bcd59f992"
},
"_from": "uglify-js@1.2.5"
}

View File

@@ -1,4 +1,5 @@
language: node_js
npm_args: --ws:native
node_js:
- 0.4
- 0.6
- 0.7

View File

@@ -1,3 +1,23 @@
v0.4.19 - June 19th, 2012
=====================
* Change sender to merge buffers for relatively small payloads, may improve perf in some cases [einaros]
* Avoid EventEmitter for Receiver classes. As above this may improve perf. [einaros]
* Renamed fallback files from the somewhat misleading '*Windows'. [einaros]
v0.4.18 - June 14th 2012
=====================
* Fixed incorrect md5 digest encoding in Hixie handshake [nicokaiser]
* Added example of use with Express 3 [einaros]
* Change installation procedure to not require --ws:native to build native extensions. They will now build if a compiler is available. [einaros]
v0.4.17 - June 13th 2012
=====================
* Improve error handling during connection handshaking [einaros]
* Ensure that errors are caught also after connection teardown [nicokaiser]
* Update 'mocha' version to 1.1.0. [einaros]
* Stop showing 'undefined' for some error logs. [tricknotes]
* Update 'should' version to 0.6.3 [tricknotes]
v0.4.16 - June 1st 2012
=====================
* Build fix for Windows. [einaros]

View File

@@ -63,6 +63,30 @@ wss.on('connection', function(ws) {
});
```
### 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
@@ -97,6 +121,8 @@ ws.on('message', function(data, flags) {
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 ###
@@ -107,14 +133,6 @@ Otherwise, see the test cases.
See the doc/ directory for Node.js-like docs for the ws classes.
## Todos ##
* Expose Sender and Receiver configuration options through WebSocket, and test that properly.
* Cleanup configuration for Sender, and add similar bits to Receiver.
* Either expose a configurable setting indicating favoring speed or memory use, or do a timer based shrink of Receiver's pools.
* Make necessary changes to also support the even older hixie-75? Or at least write a few more tests for Hixie-76 to verify that fragmented nonce transfers really work.
## License ##
(The MIT License)

View File

@@ -7,10 +7,10 @@
"url": "git://github.com/einaros/ws.git"
},
"engines": {
"node": "~0.6.8"
"node": ">0.4.0"
},
"dependencies": {
"express": "latest"
"express": "2.x"
},
"devDependencies": {},
"optionalDependencies": {}

View File

@@ -12,12 +12,13 @@
</style>
<script>
function updateStats(memuse) {
document.querySelector('div#rss').innerText = memuse.rss;
document.querySelector('div#heapTotal').innerText = memuse.heapTotal;
document.querySelector('div#heapUsed').innerText = memuse.heapUsed;
document.getElementById('rss').innerHTML = memuse.rss;
document.getElementById('heapTotal').innerHTML = memuse.heapTotal;
document.getElementById('heapUsed').innerHTML = memuse.heapUsed;
}
var ws = new WebSocket("ws://localhost:8080");
var host = window.document.location.host.replace(/:.*/, '');
var ws = new WebSocket('ws://' + host + ':8080');
ws.onmessage = function (event) {
updateStats(JSON.parse(event.data));
};

View File

@@ -4,11 +4,12 @@ var WebSocketServer = require('../../').Server
, app = express.createServer();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
var wss = new WebSocketServer({server: app});
wss.on('connection', function(ws) {
var id = setInterval(function() {
ws.send(JSON.stringify(process.memoryUsage()));
ws.send(JSON.stringify(process.memoryUsage()), function() { /* ignore errors */ });
}, 100);
console.log('started client interval');
ws.on('close', function() {
@@ -16,5 +17,3 @@ wss.on('connection', function(ws) {
clearInterval(id);
})
});
app.listen(8080);

View File

@@ -1,31 +1,29 @@
var spawn = require('child_process').spawn
, exec = require('child_process').exec;
, exec = require('child_process').exec
, tinycolor = require('tinycolor')
, fs = require('fs')
, version = JSON.parse(fs.readFileSync(__dirname + '/package.json', 'utf8')).version
, verbose = process.env['npm_package_config_verbose'] != null ? process.env['npm_package_config_verbose'] === 'true' : false;
var build_native = process.env['npm_package_config_native'] != null ? process.env['npm_package_config_native'] : 'false';
build_native = build_native == 'true' ? true : false;
if(build_native) {
process.stdout.write("================================================================================\n");
process.stdout.write("= =\n");
process.stdout.write("= Building WS with blazing fast native extensions. =\n");
process.stdout.write("= =\n");
process.stdout.write("================================================================================\n");
console.log('[ws v%s]'.blue + ' Attempting to compile blazing fast native extensions.'.green, version);
var gyp = exec('node-gyp rebuild', {cwd: __dirname});
gyp.stdout.on('data', function(data) {
process.stdout.write(data);
});
gyp.stderr.on('data', function(data) {
process.stdout.write(data);
});
gyp.on('exit', function(code) {
process.exit(code);
});
}
else {
process.stdout.write("================================================================================\n");
process.stdout.write("= =\n");
process.stdout.write("= To install WS with blazing fast native extensions, use =\n");
process.stdout.write("= <npm install ws --ws:native> =\n");
process.stdout.write("= =\n");
process.stdout.write("================================================================================\n");
}
var gyp = exec('node-gyp rebuild', {cwd: __dirname});
gyp.stdout.on('data', function(data) {
if (verbose) process.stdout.write(data);
});
gyp.stderr.on('data', function(data) {
if (verbose) process.stdout.write(data);
});
gyp.on('exit', function(code) {
if (code !== 0) {
console.log('[ws v%s]'.blue + ' Native code compile failed (but the module will still work):'.yellow, version);
console.log('[ws v%s]'.blue + ' The native extensions are faster, but not required.'.yellow, version);
console.log('[ws v%s]'.blue + ' On Windows, native extensions require Visual Studio and Python.'.yellow, version);
console.log('[ws v%s]'.blue + ' On Unix, native extensions require Python, make and a C++ compiler.'.yellow, version);
console.log('[ws v%s]'.blue + ' Start npm with --ws:verbose to show compilation output (if any).'.yellow, version);
}
else {
console.log('[ws v%s]'.blue + ' Native extension compilation successful!'.green, version);
}
process.exit();
});

View File

@@ -9,7 +9,7 @@ try {
} catch (e) { try {
module.exports = require('../build/default/bufferutil');
} catch (e) { try {
module.exports = require('./BufferUtilWindows');
module.exports = require('./BufferUtil.fallback');
} catch (e) {
console.error('bufferutil.node seems to not have been built. Run npm install.');
throw e;

View File

@@ -1,51 +0,0 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
/**
* Windows Compatibility
*/
module.exports.BufferUtil = {
merge: function(mergedBuffer, buffers) {
var offset = 0;
for (var i = 0, l = buffers.length; i < l; ++i) {
var buf = buffers[i];
buf.copy(mergedBuffer, offset);
offset += buf.length;
}
},
mask: function(source, mask, output, offset, length) {
var maskNum = mask.readUInt32LE(0, true);
var i = 0;
for (; i < length - 3; i += 4) {
var num = maskNum ^ source.readUInt32LE(i, true);
if (num < 0) num = 4294967296 + num;
output.writeUInt32LE(num, offset + i, true);
}
switch (length % 4) {
case 3: output[offset + i + 2] = source[i + 2] ^ mask[2];
case 2: output[offset + i + 1] = source[i + 1] ^ mask[1];
case 1: output[offset + i] = source[i] ^ mask[0];
case 0:;
}
},
unmask: function(data, mask) {
var maskNum = mask.readUInt32LE(0, true);
var length = data.length;
var i = 0;
for (; i < length - 3; i += 4) {
var num = maskNum ^ data.readUInt32LE(i, true);
if (num < 0) num = 4294967296 + num;
data.writeUInt32LE(num, i, true);
}
switch (length % 4) {
case 3: data[i + 2] = data[i + 2] ^ mask[2];
case 2: data[i + 1] = data[i + 1] ^ mask[1];
case 1: data[i] = data[i] ^ mask[0];
case 0:;
}
}
}

View File

@@ -4,9 +4,7 @@
* MIT Licensed
*/
var events = require('events')
, util = require('util')
, EventEmitter = events.EventEmitter;
var util = require('util');
/**
* State constants
@@ -25,16 +23,17 @@ function Receiver () {
this.messageEnd = -1;
this.spanLength = 0;
this.dead = false;
this.onerror = function() {};
this.ontext = function() {};
this.onbinary = function() {};
this.onclose = function() {};
this.onping = function() {};
this.onpong = function() {};
}
module.exports = Receiver;
/**
* Inherits from EventEmitter.
*/
util.inherits(Receiver, events.EventEmitter);
/**
* Add new data to the parser.
*
@@ -47,7 +46,7 @@ Receiver.prototype.add = function(data) {
if (self.state === EMPTY) {
if (data.length == 2 && data[0] == 0xFF && data[1] == 0x00) {
self.reset();
self.emit('close');
self.onclose();
return;
}
if (data[0] !== 0x00) {
@@ -100,7 +99,7 @@ Receiver.prototype.parse = function() {
tail = lastBuffer.slice(this.messageEnd + 1);
}
this.reset();
this.emit('text', output.toString('utf8'));
this.ontext(output.toString('utf8'));
return tail;
}
@@ -112,7 +111,7 @@ Receiver.prototype.parse = function() {
Receiver.prototype.error = function (reason, terminate) {
this.reset();
this.emit('error', reason, terminate);
this.onerror(reason, terminate);
return this;
}

View File

@@ -4,9 +4,7 @@
* MIT Licensed
*/
var events = require('events')
, util = require('util')
, EventEmitter = events.EventEmitter
var util = require('util')
, Validation = require('./Validation').Validation
, ErrorCodes = require('./ErrorCodes')
, BufferPool = require('./BufferPool')
@@ -58,16 +56,17 @@ function Receiver () {
this.currentMessage = [];
this.expectHeader(2, this.processPacket);
this.dead = false;
this.onerror = function() {};
this.ontext = function() {};
this.onbinary = function() {};
this.onclose = function() {};
this.onping = function() {};
this.onpong = function() {};
};
module.exports = Receiver;
/**
* Inherits from EventEmitter.
*/
util.inherits(Receiver, events.EventEmitter);
/**
* Add new data to the parser.
*
@@ -111,6 +110,12 @@ Receiver.prototype.cleanup = function() {
this.fragmentedBufferPool = null;
this.state = null;
this.currentMessage = null;
this.onerror = null;
this.ontext = null;
this.onbinary = null;
this.onclose = null;
this.onping = null;
this.onpong = null;
}
/**
@@ -293,7 +298,7 @@ Receiver.prototype.concatBuffers = function(buffers) {
Receiver.prototype.error = function (reason, protocolErrorCode) {
this.reset();
this.emit('error', reason, protocolErrorCode);
this.onerror(reason, protocolErrorCode);
return this;
}
@@ -389,7 +394,7 @@ var opcodes = {
this.error('invalid utf8 sequence', 1007);
return;
}
this.emit('text', messageBuffer.toString('utf8'), {masked: this.state.masked, buffer: messageBuffer});
this.ontext(messageBuffer.toString('utf8'), {masked: this.state.masked, buffer: messageBuffer});
this.currentMessage = [];
}
this.endPacket();
@@ -440,7 +445,7 @@ var opcodes = {
if (packet != null) this.currentMessage.push(packet);
if (this.state.lastFragment) {
var messageBuffer = this.concatBuffers(this.currentMessage);
this.emit('binary', messageBuffer, {masked: this.state.masked, buffer: messageBuffer});
this.onbinary(messageBuffer, {masked: this.state.masked, buffer: messageBuffer});
this.currentMessage = [];
}
this.endPacket();
@@ -501,7 +506,7 @@ var opcodes = {
}
message = messageBuffer.toString('utf8');
}
this.emit('close', code, message, {masked: self.state.masked});
this.onclose(code, message, {masked: self.state.masked});
this.reset();
},
},
@@ -540,7 +545,7 @@ var opcodes = {
}
},
finish: function(mask, data) {
this.emit('ping', this.unmask(mask, data, true), {masked: this.state.masked, binary: true});
this.onping(this.unmask(mask, data, true), {masked: this.state.masked, binary: true});
this.endPacket();
}
},
@@ -579,7 +584,7 @@ var opcodes = {
}
},
finish: function(mask, data) {
this.emit('pong', this.unmask(mask, data, true), {masked: this.state.masked, binary: true});
this.onpong(this.unmask(mask, data, true), {masked: this.state.masked, binary: true});
this.endPacket();
}
}

View File

@@ -119,9 +119,9 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
secondByte = 126;
}
var totalLength = (maskData && !canModifyData) ? dataLength + dataOffset : dataOffset;
var mergeBuffers = dataLength < 32768 || (maskData && !canModifyData);
var totalLength = mergeBuffers ? dataLength + dataOffset : dataOffset;
var outputBuffer = new Buffer(totalLength);
outputBuffer[0] = finalFragment ? opcode | 0x80 : opcode;
switch (secondByte) {
@@ -133,9 +133,6 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
writeUInt32BE.call(outputBuffer, dataLength, 6);
}
var sendsDone = 0;
var cbCaller = function() { if (++sendsDone == 2 && typeof cb == 'function') cb(null); }
if (maskData) {
outputBuffer[1] = secondByte | 0x80;
var mask = this._randomMask || (this._randomMask = getRandomMask());
@@ -143,7 +140,7 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
outputBuffer[dataOffset - 3] = mask[1];
outputBuffer[dataOffset - 2] = mask[2];
outputBuffer[dataOffset - 1] = mask[3];
if (!canModifyData) {
if (mergeBuffers) {
bufferUtil.mask(data, mask, outputBuffer, dataOffset, dataLength);
try {
this._socket.write(outputBuffer, 'binary', cb);
@@ -156,8 +153,8 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
else {
bufferUtil.mask(data, mask, data, 0, dataLength);
try {
this._socket.write(outputBuffer, 'binary', cb ? cbCaller : null);
this._socket.write(data, 'binary', cb ? cbCaller : null);
this._socket.write(outputBuffer, 'binary');
this._socket.write(data, 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
@@ -167,15 +164,27 @@ Sender.prototype.frameAndSend = function(opcode, data, finalFragment, maskData,
}
else {
outputBuffer[1] = secondByte;
if (mergeBuffers) {
data.copy(outputBuffer, dataOffset);
try {
this._socket.write(outputBuffer, 'binary', cb ? cbCaller : null);
this._socket.write(data, 'binary', cb ? cbCaller : null);
this._socket.write(outputBuffer, 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
else this.emit('error', e);
}
}
else {
try {
this._socket.write(outputBuffer, 'binary');
this._socket.write(data, 'binary', cb);
}
catch (e) {
if (typeof cb == 'function') cb(e);
else this.emit('error', e);
}
}
}
}
module.exports = Sender;

View File

@@ -9,7 +9,7 @@ try {
} catch (e) { try {
module.exports = require('../build/default/validation');
} catch (e) { try {
module.exports = require('./ValidationWindows');
module.exports = require('./Validation.fallback');
} catch (e) {
console.error('validation.node seems to not have been built. Run npm install.');
throw e;

View File

@@ -1,16 +0,0 @@
/*!
* ws: a node.js websocket client
* Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com>
* MIT Licensed
*/
/**
* Windows Compatibility
*/
module.exports.Validation = {
isValidUTF8: function(buffer) {
return true;
}
};

View File

@@ -509,32 +509,32 @@ function establishConnection(ReceiverClass, SenderClass, socket, upgradeHead) {
process.nextTick(firstHandler);
// receiver event handlers
self._receiver.on('text', function (data, flags) {
self._receiver.ontext = function (data, flags) {
flags = flags || {};
self.emit('message', data, flags);
});
self._receiver.on('binary', function (data, flags) {
};
self._receiver.onbinary = function (data, flags) {
flags = flags || {};
flags.binary = true;
self.emit('message', data, flags);
});
self._receiver.on('ping', function(data, flags) {
};
self._receiver.onping = function(data, flags) {
flags = flags || {};
self.pong(data, {mask: !self._isServer, binary: flags.binary === true}, true);
self.emit('ping', data, flags);
});
self._receiver.on('pong', function(data, flags) {
};
self._receiver.onpong = function(data, flags) {
self.emit('pong', data, flags);
});
self._receiver.on('close', function(code, data, flags) {
};
self._receiver.onclose = function(code, data, flags) {
flags = flags || {};
self.close(code, data);
});
self._receiver.on('error', function(reason, errorCode) {
};
self._receiver.onerror = function(reason, errorCode) {
// close the connection when the receiver reports a HyBi error code
self.close(typeof errorCode != 'undefined' ? errorCode : 1002, '');
self.emit('error', reason, errorCode);
});
};
// finalize the client
this._sender = new SenderClass(socket);
@@ -593,6 +593,11 @@ function cleanupWebsocketResources(error) {
this.readyState = WebSocket.CLOSED;
if (this._socket) {
removeAllListeners(this._socket);
// catch all socket error after removing all standard handlers
var socket = this._socket;
this._socket.on('error', function() {
try { socket.destroy(); } catch (e) {}
});
try {
if (!error) this._socket.end();
else this._socket.terminate();
@@ -605,7 +610,6 @@ function cleanupWebsocketResources(error) {
this._sender = null;
}
if (this._receiver) {
removeAllListeners(this._receiver);
this._receiver.cleanup();
this._receiver = null;
}

View File

@@ -15,7 +15,7 @@ var util = require('util')
, url = require('url');
/**
* WebSocket implementation
* WebSocket Server implementation
*/
function WebSocketServer(options, callback) {
@@ -40,7 +40,7 @@ function WebSocketServer(options, callback) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Not implemented');
});
this._server.listen(options.value.port, options.value.host || '127.0.0.1', callback);
this._server.listen(options.value.port, options.value.host, callback);
this._closeServer = function() { self._server.close(); };
this._server.once('listening', function() { self.emit('listening'); });
}
@@ -150,6 +150,12 @@ module.exports = WebSocketServer;
*/
function handleHybiUpgrade(req, socket, upgradeHead, cb) {
// handle premature socket errors
var errorHandler = function() {
try { socket.destroy(); } catch (e) {}
}
socket.on('error', errorHandler);
// verify key presence
if (!req.headers['sec-websocket-key']) {
abortConnection(socket, 400, 'Bad Request');
@@ -168,31 +174,9 @@ function handleHybiUpgrade(req, socket, upgradeHead, cb) {
req.headers['sec-websocket-origin'] :
req.headers['origin'];
var args = [req, socket, upgradeHead, version, cb];
if (typeof this.options.verifyClient == 'function') {
var info = {
origin: origin,
secure: typeof req.connection.encrypted !== 'undefined',
req: req
};
if (this.options.verifyClient.length == 2) {
// handler to call when the connection sequence completes
var self = this;
this.options.verifyClient(info, function(result) {
if (!result) abortConnection(socket, 401, 'Unauthorized')
else completeUpgrade.apply(self, args);
});
return;
}
else if (!this.options.verifyClient(info)) {
abortConnection(socket, 401, 'Unauthorized');
return;
}
}
completeUpgrade.apply(this, args);
}
function completeUpgrade(req, socket, upgradeHead, version, cb) {
var completeHybiUpgrade = function() {
var protocol = req.headers['sec-websocket-protocol'];
// calc key
@@ -207,9 +191,13 @@ function completeUpgrade(req, socket, upgradeHead, version, cb) {
, 'Connection: Upgrade'
, 'Sec-WebSocket-Accept: ' + key
];
if (typeof protocol != 'undefined') {
headers['Sec-WebSocket-Protocol'] = protocol;
}
socket.setTimeout(0);
socket.setNoDelay(true);
try {
socket.write(headers.concat('', '').join('\r\n'));
}
@@ -218,16 +206,14 @@ function completeUpgrade(req, socket, upgradeHead, version, cb) {
try { socket.destroy(); } catch (e) {}
return;
}
socket.setTimeout(0);
socket.setNoDelay(true);
var client = new WebSocket([req, socket, upgradeHead], {
protocolVersion: version,
protocol: protocol
});
if (this.options.clientTracking) {
this.clients.push(client);
var self = this;
if (self.options.clientTracking) {
self.clients.push(client);
client.on('close', function() {
var index = self.clients.indexOf(client);
if (index != -1) {
@@ -235,10 +221,43 @@ function completeUpgrade(req, socket, upgradeHead, version, cb) {
}
});
}
// signal upgrade complete
socket.removeListener('error', errorHandler);
cb(client);
}
// optionally call external client verification handler
if (typeof this.options.verifyClient == 'function') {
var info = {
origin: origin,
secure: typeof req.connection.encrypted !== 'undefined',
req: req
};
if (this.options.verifyClient.length == 2) {
this.options.verifyClient(info, function(result) {
if (!result) abortConnection(socket, 401, 'Unauthorized')
else completeHybiUpgrade();
});
return;
}
else if (!this.options.verifyClient(info)) {
abortConnection(socket, 401, 'Unauthorized');
return;
}
}
completeHybiUpgrade();
}
function handleHixieUpgrade(req, socket, upgradeHead, cb) {
// handle premature socket errors
var errorHandler = function() {
try { socket.destroy(); } catch (e) {}
}
socket.on('error', errorHandler);
// bail if options prevent hixie
if (this.options.disableHixie) {
abortConnection(socket, 401, 'Hixie support disabled');
return;
@@ -250,10 +269,13 @@ function handleHixieUpgrade(req, socket, upgradeHead, cb) {
return;
}
var origin = req.headers['origin']
, self = this;
// setup handshake completion to run after client has been verified
var self = this;
var onClientVerified = function() {
var protocol = req.headers['sec-websocket-protocol'];
var location = ((req.headers['x-forwarded-proto'] === 'https' || socket.encrypted) ? 'wss' : 'ws') + '://' + req.headers.host + req.url
, protocol = req.headers['sec-websocket-protocol'];
// handshake completion code to run once nonce has been successfully retrieved
var completeHandshake = function(nonce, rest) {
@@ -261,6 +283,7 @@ function handleHixieUpgrade(req, socket, upgradeHead, cb) {
var k1 = req.headers['sec-websocket-key1']
, k2 = req.headers['sec-websocket-key2']
, md5 = crypto.createHash('md5');
[k1, k2].forEach(function (k) {
var n = parseInt(k.replace(/[^\d]/g, ''))
, spaces = k.replace(/[^ ]/g, '').length;
@@ -289,19 +312,21 @@ function handleHixieUpgrade(req, socket, upgradeHead, cb) {
socket.setTimeout(0);
socket.setNoDelay(true);
try {
socket.write(headers.concat('', '').join('\r\n'));
socket.write(md5.digest('binary'), 'binary');
}
catch (e) {
try { socket.destroy(); } catch (e) {}
return;
}
// merge header and hash buffer
var headerBuffer = new Buffer(headers.concat('', '').join('\r\n'));
var hashBuffer = new Buffer(md5.digest('binary'), 'binary');
var handshakeBuffer = new Buffer(headerBuffer.length + hashBuffer.length);
headerBuffer.copy(handshakeBuffer, 0);
hashBuffer.copy(handshakeBuffer, headerBuffer.length);
// do a single write, which - upon success - causes a new client websocket to be setup
socket.write(handshakeBuffer, 'binary', function(err) {
if (err) return; // do not create client if an error happens
var client = new WebSocket([req, socket, rest], {
protocolVersion: 'hixie-76',
protocol: protocol
});
if (this.options.clientTracking) {
if (self.options.clientTracking) {
self.clients.push(client);
client.on('close', function() {
var index = self.clients.indexOf(client);
@@ -310,7 +335,16 @@ function handleHixieUpgrade(req, socket, upgradeHead, cb) {
}
});
}
// signal upgrade complete
socket.removeListener('error', errorHandler);
cb(client);
});
}
catch (e) {
try { socket.destroy(); } catch (e) {}
return;
}
}
// retrieve nonce
@@ -343,8 +377,6 @@ function handleHixieUpgrade(req, socket, upgradeHead, cb) {
}
// verify client
var location = ((req.headers['x-forwarded-proto'] === 'https' || socket.encrypted) ? 'wss' : 'ws') + '://' + req.headers.host + req.url
, origin = req.headers['origin'];
if (typeof this.options.verifyClient == 'function') {
var info = {
origin: origin,
@@ -364,6 +396,7 @@ function handleHixieUpgrade(req, socket, upgradeHead, cb) {
return;
}
}
// no client verification required
onClientVerified();
}

View File

@@ -31,8 +31,8 @@
"_id": "commander@0.5.2",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"_from": "commander@0.5.x"
}

View File

@@ -26,8 +26,8 @@
"_id": "options@0.0.3",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"_from": "options@latest"
}

View File

@@ -6,7 +6,7 @@
},
"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.16",
"version": "0.4.19",
"repository": {
"type": "git",
"url": "git://github.com/einaros/ws.git"
@@ -22,28 +22,25 @@
"node": ">=0.4.0"
},
"config": {
"native": false
"verbose": false
},
"dependencies": {
"commander": "0.5.x",
"tinycolor": "0.x",
"options": "latest"
},
"devDependencies": {
"mocha": "0.8.x",
"should": "0.4.2",
"expect.js": "0.1.2",
"mocha": "1.1.x",
"should": "0.6.x",
"expect.js": "0.1.x",
"benchmark": "0.3.x",
"tinycolor": "0.x",
"ansi": "latest"
},
"_id": "ws@0.4.16",
"_id": "ws@0.4.19",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "8a17cdef05ece01c56edd3175e607c4f1c8a77c7"
},
"_from": "ws@0.4.x"
}

View File

@@ -111,3 +111,5 @@ extern "C" void init (Handle<Object> target)
HandleScope scope;
BufferUtil::Initialize(target);
}
NODE_MODULE(bufferutil, init)

View File

@@ -67,7 +67,7 @@ static int isLegalUTF8(const uint8_t *source, const int length)
int is_valid_utf8 (size_t len, char *value)
{
/* is the string valid UTF-8? */
for (int i = 0; i < len; i++) {
for (unsigned int i = 0; i < len; i++) {
uint32_t ch = 0;
uint8_t extrabytes = trailingBytesForUTF8[(uint8_t) value[i]];
@@ -139,3 +139,5 @@ extern "C" void init (Handle<Object> target)
HandleScope scope;
Validation::Initialize(target);
}
NODE_MODULE(validation, init)

View File

@@ -9,10 +9,10 @@ describe('Receiver', function() {
var packet = '00 48 65 6c 6c 6f ff';
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal('Hello', data);
});
};
p.add(getBufferFromHexString(packet));
expect(gotData).to.equal(true);
@@ -24,10 +24,10 @@ describe('Receiver', function() {
var gotData = false;
var messages = [];
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
messages.push(data);
});
};
p.add(getBufferFromHexString(packet));
expect(gotData).to.equal(true);
@@ -41,10 +41,10 @@ describe('Receiver', function() {
var packet = '00 ff';
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal('', data);
});
};
p.add(getBufferFromHexString(packet));
expect(gotData).to.equal(true);
@@ -63,10 +63,10 @@ describe('Receiver', function() {
var gotData = false;
var messages = [];
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
messages.push(data);
});
};
for (var i = 0; i < packets.length; ++i) {
p.add(getBufferFromHexString(packets[i]));
@@ -91,13 +91,13 @@ describe('Receiver', function() {
var gotData = false;
var gotError = false;
var messages = [];
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
messages.push(data);
});
p.on('error', function(reason, code) {
};
p.onerror = function(reason, code) {
gotError = code == true;
});
};
for (var i = 0; i < packets.length && !gotError; ++i) {
p.add(getBufferFromHexString(packets[i]));
@@ -116,12 +116,12 @@ describe('Receiver', function() {
var gotClose = false;
var gotError = false;
p.on('close', function() {
p.onclose = function() {
gotClose = true;
});
p.on('error', function(reason, code) {
};
p.onerror = function(reason, code) {
gotError = code == true;
});
};
for (var i = 0; i < packets.length && !gotError; ++i) {
p.add(getBufferFromHexString(packets[i]));

View File

@@ -9,10 +9,10 @@ describe('Receiver', function() {
var packet = '81 05 48 65 6c 6c 6f';
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal('Hello', data);
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;
@@ -22,9 +22,9 @@ describe('Receiver', function() {
var packet = '88 00';
var gotClose = false;
p.on('close', function(data) {
p.onclose = function(data) {
gotClose = true;
});
};
p.add(getBufferFromHexString(packet));
gotClose.should.be.ok;
@@ -34,10 +34,10 @@ describe('Receiver', function() {
var packet = '81 93 34 83 a8 68 01 b9 92 52 4f a1 c6 09 59 e6 8a 52 16 e6 cb 00 5b a1 d5';
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal('5:::{"name":"echo"}', data);
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;
@@ -49,10 +49,10 @@ describe('Receiver', function() {
var packet = '81 FE ' + pack(4, message.length) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(message, '34 83 a8 68'));
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal(message, data);
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;
@@ -64,10 +64,10 @@ describe('Receiver', function() {
var packet = '81 FF ' + pack(16, message.length) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(message, '34 83 a8 68'));
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal(message, data);
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;
@@ -82,10 +82,10 @@ describe('Receiver', function() {
var packet2 = '80 FE ' + pack(4, msgpiece2.length) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(msgpiece2, '34 83 a8 68'));
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal(message, data);
});
};
p.add(getBufferFromHexString(packet1));
p.add(getBufferFromHexString(packet2));
@@ -97,10 +97,10 @@ describe('Receiver', function() {
var packet = '89 ' + getHybiLengthAsHexString(message.length, true) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(message, '34 83 a8 68'));
var gotPing = false;
p.on('ping', function(data) {
p.onping = function(data) {
gotPing = true;
assert.equal(message, data);
});
};
p.add(getBufferFromHexString(packet));
gotPing.should.be.ok;
@@ -110,9 +110,9 @@ describe('Receiver', function() {
var packet = '89 00';
var gotPing = false;
p.on('ping', function(data) {
p.onping = function(data) {
gotPing = true;
});
};
p.add(getBufferFromHexString(packet));
gotPing.should.be.ok;
@@ -132,15 +132,15 @@ describe('Receiver', function() {
var packet2 = '80 FE ' + pack(4, msgpiece2.length) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(msgpiece2, '34 83 a8 68'));
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal(message, data);
});
};
var gotPing = false;
p.on('ping', function(data) {
p.onping = function(data) {
gotPing = true;
assert.equal(pingMessage, data);
});
};
p.add(getBufferFromHexString(packet1));
p.add(getBufferFromHexString(pingPacket));
@@ -163,15 +163,15 @@ describe('Receiver', function() {
var packet2 = '80 FE ' + pack(4, msgpiece2.length) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(msgpiece2, '34 83 a8 68'));
var gotData = false;
p.on('text', function(data) {
p.ontext = function(data) {
gotData = true;
assert.equal(message, data);
});
};
var gotPing = false;
p.on('ping', function(data) {
p.onping = function(data) {
gotPing = true;
assert.equal(pingMessage, data);
});
};
var buffers = [];
buffers = buffers.concat(splitBuffer(getBufferFromHexString(packet1)));
@@ -192,10 +192,10 @@ describe('Receiver', function() {
var packet = '82 ' + getHybiLengthAsHexString(length, true) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(message, '34 83 a8 68'));
var gotData = false;
p.on('binary', function(data) {
p.onbinary = function(data) {
gotData = true;
assert.equal(originalMessage, getHexStringFromBuffer(data));
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;
@@ -209,10 +209,10 @@ describe('Receiver', function() {
var packet = '82 ' + getHybiLengthAsHexString(length, true) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(message, '34 83 a8 68'));
var gotData = false;
p.on('binary', function(data) {
p.onbinary = function(data) {
gotData = true;
assert.equal(originalMessage, getHexStringFromBuffer(data));
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;
@@ -226,10 +226,10 @@ describe('Receiver', function() {
var packet = '82 ' + getHybiLengthAsHexString(length, true) + ' 34 83 a8 68 ' + getHexStringFromBuffer(mask(message, '34 83 a8 68'));
var gotData = false;
p.on('binary', function(data) {
p.onbinary = function(data) {
gotData = true;
assert.equal(originalMessage, getHexStringFromBuffer(data));
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;
@@ -243,10 +243,10 @@ describe('Receiver', function() {
var packet = '82 ' + getHybiLengthAsHexString(length, false) + ' ' + getHexStringFromBuffer(message);
var gotData = false;
p.on('binary', function(data) {
p.onbinary = function(data) {
gotData = true;
assert.equal(originalMessage, getHexStringFromBuffer(data));
});
};
p.add(getBufferFromHexString(packet));
gotData.should.be.ok;

View File

@@ -64,28 +64,28 @@ function validServer(server, req, socket) {
var sender = new Sender(socket);
var receiver = new Receiver();
receiver.on('text', function (message, flags) {
receiver.ontext = function (message, flags) {
server.emit('message', message, flags);
sender.send(message);
});
receiver.on('binary', function (message, flags) {
};
receiver.onbinary = function (message, flags) {
flags = flags || {};
flags.binary = true;
server.emit('message', message, flags);
sender.send(message, {binary: true});
});
receiver.on('ping', function (message, flags) {
};
receiver.onping = function (message, flags) {
flags = flags || {};
server.emit('ping', message, flags);
});
receiver.on('pong', function (message, flags) {
};
receiver.onpong = function (message, flags) {
flags = flags || {};
server.emit('pong', message, flags);
});
receiver.on('close', function (code, message, flags) {
};
receiver.onclose = function (code, message, flags) {
flags = flags || {};
server.emit('close', code, message, flags);
});
};
socket.on('data', function (data) {
receiver.add(data);
});

View File

@@ -27,11 +27,8 @@
"node": "*"
},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "952016329fbc35095f12d39b7f8183ad651c0f3c"
},
"_from": "xmlhttprequest@1.2.2"
}

View File

@@ -59,11 +59,8 @@
"_id": "socket.io-client@0.9.6",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"dist": {
"shasum": "a6cb206a92d73463498aeb4b5d84f3db95f17ec1"
},
"_from": "socket.io-client@0.9.6"
}

View File

@@ -59,8 +59,8 @@
"_id": "socket.io@0.9.6",
"optionalDependencies": {},
"_engineSupported": true,
"_npmVersion": "1.1.19",
"_nodeVersion": "v0.6.17",
"_npmVersion": "1.1.24",
"_nodeVersion": "v0.6.19",
"_defaultsLoaded": true,
"_from": "socket.io@>= 0.0.1"
}