summaryrefslogtreecommitdiff
path: root/node_modules/ws/examples/fileapi
diff options
context:
space:
mode:
Diffstat (limited to 'node_modules/ws/examples/fileapi')
-rw-r--r--node_modules/ws/examples/fileapi/.npmignore1
-rw-r--r--node_modules/ws/examples/fileapi/package.json18
-rw-r--r--node_modules/ws/examples/fileapi/public/app.js39
-rw-r--r--node_modules/ws/examples/fileapi/public/index.html22
-rw-r--r--node_modules/ws/examples/fileapi/public/uploader.js55
-rw-r--r--node_modules/ws/examples/fileapi/server.js103
6 files changed, 238 insertions, 0 deletions
diff --git a/node_modules/ws/examples/fileapi/.npmignore b/node_modules/ws/examples/fileapi/.npmignore
new file mode 100644
index 0000000..dcd5756
--- /dev/null
+++ b/node_modules/ws/examples/fileapi/.npmignore
@@ -0,0 +1 @@
+uploaded
diff --git a/node_modules/ws/examples/fileapi/package.json b/node_modules/ws/examples/fileapi/package.json
new file mode 100644
index 0000000..7816f27
--- /dev/null
+++ b/node_modules/ws/examples/fileapi/package.json
@@ -0,0 +1,18 @@
+{
+ "author": "",
+ "name": "fileapi",
+ "version": "0.0.0",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/einaros/ws.git"
+ },
+ "engines": {
+ "node": "~0.6.8"
+ },
+ "dependencies": {
+ "express": "latest",
+ "ansi": "https://github.com/einaros/ansi.js/tarball/master"
+ },
+ "devDependencies": {},
+ "optionalDependencies": {}
+}
diff --git a/node_modules/ws/examples/fileapi/public/app.js b/node_modules/ws/examples/fileapi/public/app.js
new file mode 100644
index 0000000..e812cc3
--- /dev/null
+++ b/node_modules/ws/examples/fileapi/public/app.js
@@ -0,0 +1,39 @@
+function onFilesSelected(e) {
+ var button = e.srcElement;
+ button.disabled = true;
+ var progress = document.querySelector('div#progress');
+ progress.innerHTML = '0%';
+ var files = e.target.files;
+ var totalFiles = files.length;
+ var filesSent = 0;
+ if (totalFiles) {
+ var uploader = new Uploader('ws://localhost:8080', function () {
+ Array.prototype.slice.call(files, 0).forEach(function(file) {
+ if (file.name == '.') {
+ --totalFiles;
+ return;
+ }
+ uploader.sendFile(file, function(error) {
+ if (error) {
+ console.log(error);
+ return;
+ }
+ ++filesSent;
+ progress.innerHTML = ~~(filesSent / totalFiles * 100) + '%';
+ console.log('Sent: ' + file.name);
+ });
+ });
+ });
+ }
+ uploader.ondone = function() {
+ uploader.close();
+ progress.innerHTML = '100% done, ' + totalFiles + ' files sent.';
+ }
+}
+
+window.onload = function() {
+ var importButtons = document.querySelectorAll('[type="file"]');
+ Array.prototype.slice.call(importButtons, 0).forEach(function(importButton) {
+ importButton.addEventListener('change', onFilesSelected, false);
+ });
+}
diff --git a/node_modules/ws/examples/fileapi/public/index.html b/node_modules/ws/examples/fileapi/public/index.html
new file mode 100644
index 0000000..0d463dd
--- /dev/null
+++ b/node_modules/ws/examples/fileapi/public/index.html
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <style>
+ body {
+ font-family: Tahoma, Geneva, sans-serif;
+ }
+ div {
+ display: inline;
+ }
+ </style>
+ <script src='uploader.js'></script>
+ <script src='app.js'></script>
+ </head>
+ <body>
+ <p>This example will upload an entire directory tree to the node.js server via a fast and persistent WebSocket connection.</p>
+ <p>Note that the example is Chrome only for now.</p>
+ <input type="file" webkitdirectory /><br/><br/>
+ Upload status:
+ <div id='progress'>Please select a directory to upload.</div>
+ </body>
+</html>
diff --git a/node_modules/ws/examples/fileapi/public/uploader.js b/node_modules/ws/examples/fileapi/public/uploader.js
new file mode 100644
index 0000000..0c34a7f
--- /dev/null
+++ b/node_modules/ws/examples/fileapi/public/uploader.js
@@ -0,0 +1,55 @@
+function Uploader(url, cb) {
+ this.ws = new WebSocket(url);
+ if (cb) this.ws.onopen = cb;
+ this.sendQueue = [];
+ this.sending = null;
+ this.sendCallback = null;
+ this.ondone = null;
+ var self = this;
+ this.ws.onmessage = function(event) {
+ var data = JSON.parse(event.data);
+ if (data.event == 'complete') {
+ if (data.path != self.sending.path) {
+ self.sendQueue = [];
+ self.sending = null;
+ self.sendCallback = null;
+ throw new Error('Got message for wrong file!');
+ }
+ self.sending = null;
+ var callback = self.sendCallback;
+ self.sendCallback = null;
+ if (callback) callback();
+ if (self.sendQueue.length === 0 && self.ondone) self.ondone(null);
+ if (self.sendQueue.length > 0) {
+ var args = self.sendQueue.pop();
+ setTimeout(function() { self.sendFile.apply(self, args); }, 0);
+ }
+ }
+ else if (data.event == 'error') {
+ self.sendQueue = [];
+ self.sending = null;
+ var callback = self.sendCallback;
+ self.sendCallback = null;
+ var error = new Error('Server reported send error for file ' + data.path);
+ if (callback) callback(error);
+ if (self.ondone) self.ondone(error);
+ }
+ }
+}
+
+Uploader.prototype.sendFile = function(file, cb) {
+ if (this.ws.readyState != WebSocket.OPEN) throw new Error('Not connected');
+ if (this.sending) {
+ this.sendQueue.push(arguments);
+ return;
+ }
+ var fileData = { name: file.name, path: file.webkitRelativePath };
+ this.sending = fileData;
+ this.sendCallback = cb;
+ this.ws.send(JSON.stringify(fileData));
+ this.ws.send(file);
+}
+
+Uploader.prototype.close = function() {
+ this.ws.close();
+}
diff --git a/node_modules/ws/examples/fileapi/server.js b/node_modules/ws/examples/fileapi/server.js
new file mode 100644
index 0000000..badfeba
--- /dev/null
+++ b/node_modules/ws/examples/fileapi/server.js
@@ -0,0 +1,103 @@
+var WebSocketServer = require('../../').Server
+ , express = require('express')
+ , fs = require('fs')
+ , http = require('http')
+ , util = require('util')
+ , path = require('path')
+ , app = express.createServer()
+ , events = require('events')
+ , ansi = require('ansi')
+ , cursor = ansi(process.stdout);
+
+function BandwidthSampler(ws, interval) {
+ interval = interval || 2000;
+ var previousByteCount = 0;
+ var self = this;
+ var intervalId = setInterval(function() {
+ var byteCount = ws.bytesReceived;
+ var bytesPerSec = (byteCount - previousByteCount) / (interval / 1000);
+ previousByteCount = byteCount;
+ self.emit('sample', bytesPerSec);
+ }, interval);
+ ws.on('close', function() {
+ clearInterval(intervalId);
+ });
+}
+util.inherits(BandwidthSampler, events.EventEmitter);
+
+function makePathForFile(filePath, prefix, cb) {
+ if (typeof cb !== 'function') throw new Error('callback is required');
+ filePath = path.dirname(path.normalize(filePath)).replace(/^(\/|\\)+/, '');
+ var pieces = filePath.split(/(\\|\/)/);
+ var incrementalPath = prefix;
+ function step(error) {
+ if (error) return cb(error);
+ if (pieces.length == 0) return cb(null, incrementalPath);
+ incrementalPath += '/' + pieces.shift();
+ fs.exists(incrementalPath, function(exists) {
+ if (!exists) fs.mkdir(incrementalPath, step);
+ else process.nextTick(step);
+ });
+ }
+ step();
+}
+
+cursor.eraseData(2).goto(1, 1);
+app.use(express.static(__dirname + '/public'));
+
+var clientId = 0;
+var wss = new WebSocketServer({server: app});
+wss.on('connection', function(ws) {
+ var thisId = ++clientId;
+ cursor.goto(1, 4 + thisId).eraseLine();
+ console.log('Client #%d connected', thisId);
+
+ var sampler = new BandwidthSampler(ws);
+ sampler.on('sample', function(bps) {
+ cursor.goto(1, 4 + thisId).eraseLine();
+ console.log('WebSocket #%d incoming bandwidth: %d MB/s', thisId, Math.round(bps / (1024*1024)));
+ });
+
+ var filesReceived = 0;
+ var currentFile = null;
+ ws.on('message', function(data, flags) {
+ if (!flags.binary) {
+ currentFile = JSON.parse(data);
+ // note: a real-world app would want to sanity check the data
+ }
+ else {
+ if (currentFile == null) return;
+ makePathForFile(currentFile.path, __dirname + '/uploaded', function(error, path) {
+ if (error) {
+ console.log(error);
+ ws.send(JSON.stringify({event: 'error', path: currentFile.path, message: error.message}));
+ return;
+ }
+ fs.writeFile(path + '/' + currentFile.name, data, function(error) {
+ ++filesReceived;
+ // console.log('received %d bytes long file, %s', data.length, currentFile.path);
+ ws.send(JSON.stringify({event: 'complete', path: currentFile.path}));
+ currentFile = null;
+ });
+ });
+ }
+ });
+
+ ws.on('close', function() {
+ cursor.goto(1, 4 + thisId).eraseLine();
+ console.log('Client #%d disconnected. %d files received.', thisId, filesReceived);
+ });
+
+ ws.on('error', function(e) {
+ cursor.goto(1, 4 + thisId).eraseLine();
+ console.log('Client #%d error: %s', thisId, e.message);
+ });
+});
+
+fs.mkdir(__dirname + '/uploaded', function(error) {
+ // ignore errors, most likely means directory exists
+ console.log('Uploaded files will be saved to %s/uploaded.', __dirname);
+ console.log('Remember to wipe this directory if you upload lots and lots.');
+ app.listen(8080);
+ console.log('Listening on http://localhost:8080');
+});