<|start_filename|>webroot/u6_websocket/node_modules/websocket/test/libwebsockets-test-client.js<|end_filename|>
#!/usr/bin/env node
/************************************************************************
 *  Copyright 2010-2011 Worlize Inc.
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 ***********************************************************************/

var WebSocketClient = require('../lib/WebSocketClient');

var args = { /* defaults */
    secure: false
};

/* Parse command line options */
var pattern = /^--(.*?)(?:=(.*))?$/;
process.argv.forEach(function(value) {
    var match = pattern.exec(value);
    if (match) {
        args[match[1]] = match[2] ? match[2] : true;
    }
});

args.protocol = args.secure ? 'wss:' : 'ws:'

if (!args.host || !args.port) {
    console.log("WebSocket-Node: Test client for Andy Green's libwebsockets-test-server");
    console.log("Usage: ./libwebsockets-test-client.js --host=127.0.0.1 --port=8080 [--secure]");
    console.log("");
    return;
}

var mirrorClient = new WebSocketClient();

mirrorClient.on('connectFailed', function(error) {
    console.log("Connect Error: " + error.toString());
});

mirrorClient.on('connect', function(connection) {
    console.log("lws-mirror-protocol connected");
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log("lws-mirror-protocol Connection Closed");
    });  
    function spamCircles() {
        if (connection.connected) {
            // c #7A9237 487 181 14;
            var color = 0x800000 + Math.round(Math.random() * 0x7FFFFF);
            var x = Math.round(Math.random() * 502);
            var y = Math.round(Math.random() * 306);
            var radius = Math.round(Math.random() * 30);
            connection.send("c #" + color.toString(16) + " " + x + " " + y + " " + radius + ";");
            setTimeout(spamCircles, 10);
        }
    }
    spamCircles();
});

mirrorClient.connect(args.protocol + '//' + args.host + ':' + args.port + '/', 'lws-mirror-protocol');


var incrementClient = new WebSocketClient();

incrementClient.on('connectFailed', function(error) {
    console.log("Connect Error: " + error.toString());
});

incrementClient.on('connect', function(connection) {
    console.log("dumb-increment-protocol connected");
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log("dumb-increment-protocol Connection Closed");
    })
    connection.on('message', function(message) {
        console.log("Number: '" + message.utf8Data + "'");
    });
});

incrementClient.connect(args.protocol + '//' + args.host + ':' + args.port + '/', 'dumb-increment-protocol');


<|start_filename|>webroot/u6_websocket/node_modules/websocket/example/whiteboard/public/client.js<|end_filename|>
/************************************************************************
 *  Copyright 2010-2011 Worlize Inc.
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 ***********************************************************************/

function Whiteboard(canvasId) {
    this.initCanvas(canvasId);
    
    // Define accepted commands
    this.messageHandlers = {
        initCommands: this.initCommands.bind(this),
        drawLine: this.drawLine.bind(this),
        clear: this.clear.bind(this)
    };

    // Initial state
    this.lastPoint = null;
    this.mouseDown = false;
    this.color = {
        r: 0,
        g: 0,
        b: 0
    };
};

Whiteboard.prototype.connect = function() {
    var url = "ws://" + document.URL.substr(7).split('/')[0];
    
    var wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket;
    this.socket = new wsCtor(url, 'whiteboard-example');

    this.socket.onmessage = this.handleWebsocketMessage.bind(this);
    this.socket.onclose = this.handleWebsocketClose.bind(this);

    this.addCanvasEventListeners();
};

Whiteboard.prototype.handleWebsocketMessage = function(message) {
    try {
        var command = JSON.parse(message.data);
    }
    catch(e) { /* do nothing */ }
    
    if (command) {
        this.dispatchCommand(command);
    }
};

Whiteboard.prototype.handleWebsocketClose = function() {
    alert("WebSocket Connection Closed.");
};

Whiteboard.prototype.dispatchCommand = function(command) {
    // Do we have a handler function for this command?
    var handler = this.messageHandlers[command.msg];
    if (typeof(handler) === 'function') {
        // If so, call it and pass the parameter data
        handler.call(this, command.data);
    }
};

Whiteboard.prototype.initCommands = function(commandList) {
    /* Upon connection, the contents of the whiteboard
       are drawn by replaying all commands since the
       last time it was cleared */
    commandList.forEach(function(command) {
        this.dispatchCommand(command);
    }.bind(this));
};

Whiteboard.prototype.sendClear = function() {
    this.socket.send(JSON.stringify({ msg: 'clear' }));
};

Whiteboard.prototype.setColor = function(r,g,b) {
    this.color = {
        r: r,
        g: g,
        b: b
    };
};

Whiteboard.prototype.drawLine = function(data) {
    // Set the color
    var color = data.color;
    this.ctx.strokeStyle = 'rgb(' + color.r + "," + color.g + "," + color.b +')';

    this.ctx.beginPath();
    
    var points = data.points;
    // Starting point
    this.ctx.moveTo(points[0]+0.5, points[1]+0.5);
    
    // Ending point
    this.ctx.lineTo(points[2]+0.5, points[3]+0.5);
    
    this.ctx.stroke();
};

Whiteboard.prototype.clear = function() {
    this.canvas.width = this.canvas.width;
};

Whiteboard.prototype.handleMouseDown = function(event) {
    this.mouseDown = true;
	this.lastPoint = this.resolveMousePosition(event);
};

Whiteboard.prototype.handleMouseUp = function(event) {
    this.mouseDown = false;
    this.lastPoint = null;
};

Whiteboard.prototype.handleMouseMove = function(event) {
    if (!this.mouseDown) { return; }

    var currentPoint = this.resolveMousePosition(event);

    // Send a draw command to the server.
    // The actual line is drawn when the command
    // is received back from the server.
    this.socket.send(JSON.stringify({
        msg: 'drawLine',
        data: {
            color: this.color,
            points: [
                this.lastPoint.x,
                this.lastPoint.y,
                currentPoint.x,
                currentPoint.y
            ]
        }
    }));
    
    this.lastPoint = currentPoint;
};

Whiteboard.prototype.initCanvas = function(canvasId) {
    this.canvasId = canvasId;
    this.canvas = document.getElementById(canvasId);
    this.ctx = this.canvas.getContext('2d');
    this.initCanvasOffset();
};

Whiteboard.prototype.initCanvasOffset = function() {
    this.offsetX = this.offsetY = 0;
    var element = this.canvas;
    if (element.offsetParent) {
        do {
            this.offsetX += element.offsetLeft;
            this.offsetY += element.offsetTop;
        }
        while ((element = element.offsetParent));
    }
};

Whiteboard.prototype.addCanvasEventListeners = function() {
    this.canvas.addEventListener(
        'mousedown', this.handleMouseDown.bind(this), false);
    
    window.document.addEventListener(
        'mouseup', this.handleMouseUp.bind(this), false);
        
    this.canvas.addEventListener(
        'mousemove', this.handleMouseMove.bind(this), false);
};

Whiteboard.prototype.resolveMousePosition = function(event) {
    var x, y;
	if (event.offsetX) {
		x = event.offsetX;
		y = event.offsetY;
	} else {
		x = event.layerX - this.offsetX;
		y = event.layerY - this.offsetY;
	}
	return { x: x, y: y };
};


<|start_filename|>webroot/u6_websocket/node_modules/websocket/lib/utils.js<|end_filename|>
module.exports = {
    extend: function extend(dest, source) {
        for (var prop in source) {
            dest[prop] = source[prop];
        }
    }
};

<|start_filename|>webroot/u6_websocket/node_modules/websocket/example/whiteboard/package.json<|end_filename|>
{
    "name": "websocket-whiteboard"
  , "description": "example whiteboard application with websockets"
  , "version": "0.0.1"
  , "dependencies": {
        "express": "2.3.11",
        "ejs": "0.4.3"
    }
}


<|start_filename|>webroot/u6_websocket/node_modules/websocket/test/autobahn-test-client.js<|end_filename|>
#!/usr/bin/env node
/************************************************************************
 *  Copyright 2010-2011 Worlize Inc.
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 ***********************************************************************/

var WebSocketClient = require('../lib/WebSocketClient');
var wsVersion = require('../lib/websocket').version;
var querystring = require('querystring');

var args = { /* defaults */
    secure: false,
    port: '9000',
    host: 'localhost'
};

/* Parse command line options */
var pattern = /^--(.*?)(?:=(.*))?$/;
process.argv.forEach(function(value) {
    var match = pattern.exec(value);
    if (match) {
        args[match[1]] = match[2] ? match[2] : true;
    }
});

args.protocol = args.secure ? 'wss:' : 'ws:'

console.log("WebSocket-Node: Echo test client for running against the Autobahn test suite");
console.log("Usage: ./libwebsockets-test-client.js --host=127.0.0.1 --port=9000 [--secure]");
console.log("");


console.log("Starting test run.");

getCaseCount(function(caseCount) {
    var currentCase = 1;
    runNextTestCase();
    
    function runNextTestCase() {
        runTestCase(currentCase++, caseCount, function() {
            if (currentCase <= caseCount) {
                process.nextTick(runNextTestCase);
            }
            else {
                process.nextTick(function() {
                    console.log("Test suite complete, generating report.");
                    updateReport(function() {
                        console.log("Report generated.");
                    });
                });
            }
        });
    }
});


function runTestCase(caseIndex, caseCount, callback) {
    console.log("Running test " + caseIndex + " of " + caseCount);
    var echoClient = new WebSocketClient({
        maxReceivedFrameSize: 64*1024*1024,   // 64MiB
        maxReceivedMessageSize: 64*1024*1024, // 64MiB
        fragmentOutgoingMessages: false,
        keepalive: false,
        disableNagleAlgorithm: false
    });

    echoClient.on('connectFailed', function(error) {
        console.log("Connect Error: " + error.toString());
    });

    echoClient.on('connect', function(connection) {
        connection.on('error', function(error) {
            console.log("Connection Error: " + error.toString());
        });
        connection.on('close', function() {
            callback();
        });
        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                connection.sendUTF(message.utf8Data);
            }
            else if (message.type === 'binary') {
                connection.sendBytes(message.binaryData);
            }
        });
    });
    
    var qs = querystring.stringify({
        case: caseIndex,
        agent: "WebSocket-Node Client v" + wsVersion
    });
    var url = "ws://" + args.host + ":" + args.port + "/runCase?" + qs;
    echoClient.connect("ws://" + args.host + ":" + args.port + "/runCase?" + qs, []);
}

function getCaseCount(callback) {
    var client = new WebSocketClient();
    var caseCount = NaN;
    client.on('connect', function(connection) {
        connection.on('close', function() {
            callback(caseCount);
        });
        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                console.log("Got case count: " + message.utf8Data);
                caseCount = parseInt(message.utf8Data, 10);
            }
            else if (message.type === 'binary') {
                throw new Error("Unexpected binary message when retrieving case count");
            }
        });
    });
    client.connect('ws://' + args.host + ':' + args.port + '/getCaseCount', []);
}

function updateReport(callback) {
    var client = new WebSocketClient();
    var qs = querystring.stringify({
        agent: "WebSocket-Node Client v" + wsVersion
    });
    client.on('connect', function(connection) {
        connection.on('close', callback);
    });
    client.connect('ws://localhost:9000/updateReports?' + qs);
}

<|start_filename|>webroot/u6_websocket/node_modules/websocket/example/whiteboard/whiteboard.js<|end_filename|>
#!/usr/bin/env node
/************************************************************************
 *  Copyright 2010-2011 Worlize Inc.
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 ***********************************************************************/

var WebSocketServer = require('../../lib/websocket').server;
var express = require('express');

var app = express.createServer();

app.configure(function() {
    app.use(express.static(__dirname + "/public"));
    app.set('views', __dirname);
    app.set('view engine', 'ejs');
});
app.get('/', function(req, res) {
    res.render('index', { layout: false });
});
app.listen(8080);


var wsServer = new WebSocketServer({
    httpServer: app,
    
    // Firefox 7 alpha has a bug that drops the
    // connection on large fragmented messages
    fragmentOutgoingMessages: false
});

var connections = [];
var canvasCommands = [];

wsServer.on('request', function(request) {
    var connection = request.accept('whiteboard-example', request.origin);
    connections.push(connection);
    
    console.log(connection.remoteAddress + " connected - Protocol Version " + connection.websocketVersion);
    
    // Send all the existing canvas commands to the new client
    connection.sendUTF(JSON.stringify({
        msg: "initCommands",
        data: canvasCommands
    }));
    
    // Handle closed connections
    connection.on('close', function() {
        console.log(connection.remoteAddress + " disconnected");
        
        var index = connections.indexOf(connection);
        if (index !== -1) {
            // remove the connection from the pool
            connections.splice(index, 1);
        }
    });
    
    // Handle incoming messages
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            try {
                var command = JSON.parse(message.utf8Data);

                if (command.msg === 'clear') {
                    canvasCommands = [];
                }
                else {
                    canvasCommands.push(command);
                }

                // rebroadcast command to all clients
                connections.forEach(function(destination) {
                    destination.sendUTF(message.utf8Data);
                });
            }
            catch(e) {
                // do nothing if there's an error.
            }
        }
    });
});

console.log("Whiteboard test app ready");
