pax_global_header00006660000000000000000000000064122600125500014503gustar00rootroot0000000000000052 comment=fa7dcf365c1f8ec912f60e4946acc12080467377 faye-websocket-node-0.7.2/000077500000000000000000000000001226001255000153445ustar00rootroot00000000000000faye-websocket-node-0.7.2/.gitignore000066400000000000000000000000151226001255000173300ustar00rootroot00000000000000node_modules faye-websocket-node-0.7.2/.npmignore000066400000000000000000000000711226001255000173410ustar00rootroot00000000000000.git .gitignore .npmignore .travis.yml node_modules spec faye-websocket-node-0.7.2/.travis.yml000066400000000000000000000002541226001255000174560ustar00rootroot00000000000000language: node_js node_js: - "0.6" - "0.8" - "0.10" - "0.11" before_install: - '[ "${TRAVIS_NODE_VERSION}" = "0.6" ] && npm conf set strict-ssl false || true' faye-websocket-node-0.7.2/CHANGELOG.md000066400000000000000000000037551226001255000171670ustar00rootroot00000000000000### 0.7.2 / 2013-12-29 * Make sure the `close` event is emitted by clients on Node v0.10 ### 0.7.1 / 2013-12-03 * Support the `maxLength` websocket-driver option * Make the client emit `error` events on network errors ### 0.7.0 / 2013-09-09 * Allow the server to send custom headers with EventSource responses ### 0.6.1 / 2013-07-05 * Add `ca` option to the client for specifying certificate authorities * Start the server driver asynchronously so that `onopen` handlers can be added ### 0.6.0 / 2013-05-12 * Add support for custom headers ### 0.5.0 / 2013-05-05 * Extract the protocol handlers into the `websocket-driver` library * Support the Node streaming API ### 0.4.4 / 2013-02-14 * Emit the `close` event if TCP is closed before CLOSE frame is acked ### 0.4.3 / 2012-07-09 * Add `Connection: close` to EventSource response * Handle situations where `request.socket` is undefined ### 0.4.2 / 2012-04-06 * Add WebSocket error code `1011`. * Handle URLs with no path correctly by sending `GET /` ### 0.4.1 / 2012-02-26 * Treat anything other than a `Buffer` as a string when calling `send()` ### 0.4.0 / 2012-02-13 * Add `ping()` method to server-side `WebSocket` and `EventSource` * Buffer `send()` calls until the draft-76 handshake is complete * Fix HTTPS problems on Node 0.7 ### 0.3.1 / 2012-01-16 * Call `setNoDelay(true)` on `net.Socket` objects to reduce latency ### 0.3.0 / 2012-01-13 * Add support for `EventSource` connections ### 0.2.0 / 2011-12-21 * Add support for `Sec-WebSocket-Protocol` negotiation * Support `hixie-76` close frames and 75/76 ignored segments * Improve performance of HyBi parsing/framing functions * Decouple parsers from TCP and reduce write volume ### 0.1.2 / 2011-12-05 * Detect closed sockets on the server side when TCP connection breaks * Make `hixie-76` sockets work through HAProxy ### 0.1.1 / 2011-11-30 * Fix `addEventListener()` interface methods ### 0.1.0 / 2011-11-27 * Initial release, based on WebSocket components from Faye faye-websocket-node-0.7.2/README.md000066400000000000000000000247451226001255000166370ustar00rootroot00000000000000# faye-websocket * Travis CI build: [![Build status](https://secure.travis-ci.org/faye/faye-websocket-node.png)](http://travis-ci.org/faye/faye-websocket-node) * Autobahn tests: [server](http://faye.jcoglan.com/autobahn/servers/), [client](http://faye.jcoglan.com/autobahn/clients/) This is a general-purpose WebSocket implementation extracted from the [Faye](http://faye.jcoglan.com) project. It provides classes for easily building WebSocket servers and clients in Node. It does not provide a server itself, but rather makes it easy to handle WebSocket connections within an existing [Node](http://nodejs.org/) application. It does not provide any abstraction other than the standard [WebSocket API](http://dev.w3.org/html5/websockets/). It also provides an abstraction for handling [EventSource](http://dev.w3.org/html5/eventsource/) connections, which are one-way connections that allow the server to push data to the client. They are based on streaming HTTP responses and can be easier to access via proxies than WebSockets. ## Installation ``` $ npm install faye-websocket ``` ## Handling WebSocket connections in Node You can handle WebSockets on the server side by listening for HTTP Upgrade requests, and creating a new socket for the request. This socket object exposes the usual WebSocket methods for receiving and sending messages. For example this is how you'd implement an echo server: ```js var WebSocket = require('faye-websocket'), http = require('http'); var server = http.createServer(); server.on('upgrade', function(request, socket, body) { if (WebSocket.isWebSocket(request)) { var ws = new WebSocket(request, socket, body); ws.on('message', function(event) { ws.send(event.data); }); ws.on('close', function(event) { console.log('close', event.code, event.reason); ws = null; }); } }); server.listen(8000); ``` `WebSocket` objects are also duplex streams, so you could replace the `ws.on('message', ...)` line with: ```js ws.pipe(ws); ``` Note that under certain circumstances (notably a draft-76 client connecting through an HTTP proxy), the WebSocket handshake will not be complete after you call `new WebSocket()` because the server will not have received the entire handshake from the client yet. In this case, calls to `ws.send()` will buffer the message in memory until the handshake is complete, at which point any buffered messages will be sent to the client. If you need to detect when the WebSocket handshake is complete, you can use the `onopen` event. If the connection's protocol version supports it, you can call `ws.ping()` to send a ping message and wait for the client's response. This method takes a message string, and an optional callback that fires when a matching pong message is received. It returns `true` iff a ping message was sent. If the client does not support ping/pong, this method sends no data and returns `false`. ```js ws.ping('Mic check, one, two', function() { // fires when pong is received }); ``` ## Using the WebSocket client The client supports both the plain-text `ws` protocol and the encrypted `wss` protocol, and has exactly the same interface as a socket you would use in a web browser. On the wire it identifies itself as `hybi-13`. ```js var WebSocket = require('faye-websocket'), ws = new WebSocket.Client('ws://www.example.com/'); ws.on('open', function(event) { console.log('open'); ws.send('Hello, world!'); }); ws.on('message', function(event) { console.log('message', event.data); }); ws.on('close', function(event) { console.log('close', event.code, event.reason); ws = null; }); ``` The WebSocket client also lets you inspect the status and headers of the handshake response via its `statusCode` and `headers` properties. ## Subprotocol negotiation The WebSocket protocol allows peers to select and identify the application protocol to use over the connection. On the client side, you can set which protocols the client accepts by passing a list of protocol names when you construct the socket: ```js var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']); ``` On the server side, you can likewise pass in the list of protocols the server supports after the other constructor arguments: ```js var ws = new WebSocket(request, socket, body, ['irc', 'amqp']); ``` If the client and server agree on a protocol, both the client- and server-side socket objects expose the selected protocol through the `ws.protocol` property. ## Initialization options Both the server- and client-side classes allow an options object to be passed in at initialization time, for example: ```js var ws = new WebSocket(request, socket, body, protocols, options); var ws = new WebSocket.Client(url, protocols, options); ``` `protocols` is an array of subprotocols as described above, or `null`. `options` is an optional object containing any of these fields: * `headers` - an object containing key-value pairs representing HTTP headers to be sent during the handshake process * `maxLength` - the maximum allowed size of incoming message frames, in bytes. The default value is `2^26 - 1`, or 1 byte short of 64 MiB. * `ping` - an integer that sets how often the WebSocket should send ping frames, measured in seconds ## WebSocket API Both server- and client-side `WebSocket` objects support the following API. * `on('open', function(event) {})` fires when the socket connection is established. Event has no attributes. * `on('message', function(event) {})` fires when the socket receives a message. Event has one attribute, `data`, which is either a `String` (for text frames) or a `Buffer` (for binary frames). * `on('error', function(event) {})` fires when there is a protocol error due to bad data sent by the other peer. This event is purely informational, you do not need to implement error recover. * `on('close', function(event) {})` fires when either the client or the server closes the connection. Event has two optional attributes, `code` and `reason`, that expose the status code and message sent by the peer that closed the connection. * `send(message)` accepts either a `String` or a `Buffer` and sends a text or binary message over the connection to the other peer. * `ping(message = '', function() {})` sends a ping frame with an optional message and fires the callback when a matching pong is received. * `close(code, reason)` closes the connection, sending the given status code and reason text, both of which are optional. * `version` is a string containing the version of the `WebSocket` protocol the connection is using. * `protocol` is a string (which may be empty) identifying the subprotocol the socket is using. ## Handling EventSource connections in Node EventSource connections provide a very similar interface, although because they only allow the server to send data to the client, there is no `onmessage` API. EventSource allows the server to push text messages to the client, where each message has an optional event-type and ID. ```js var WebSocket = require('faye-websocket'), EventSource = WebSocket.EventSource, http = require('http'); var server = http.createServer(); server.on('request', function(request, response) { if (EventSource.isEventSource(request)) { var es = new EventSource(request, response); console.log('open', es.url, es.lastEventId); // Periodically send messages var loop = setInterval(function() { es.send('Hello') }, 1000); es.on('close', function() { clearInterval(loop); es = null; }); } else { // Normal HTTP request response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello'); } }); server.listen(8000); ``` The `send` method takes two optional parameters, `event` and `id`. The default event-type is `'message'` with no ID. For example, to send a `notification` event with ID `99`: ```js es.send('Breaking News!', {event: 'notification', id: '99'}); ``` The `EventSource` object exposes the following properties: * `url` is a string containing the URL the client used to create the EventSource. * `lastEventId` is a string containing the last event ID received by the client. You can use this when the client reconnects after a dropped connection to determine which messages need resending. When you initialize an EventSource with ` new EventSource()`, you can pass configuration options after the `response` parameter. Available options are: * `headers` is an object containing custom headers to be set on the EventSource response. * `retry` is a number that tells the client how long (in seconds) it should wait after a dropped connection before attempting to reconnect. * `ping` is a number that tells the server how often (in seconds) to send 'ping' packets to the client to keep the connection open, to defeat timeouts set by proxies. The client will ignore these messages. For example, this creates a connection that allows access from any origin, pings every 15 seconds and is retryable every 10 seconds if the connection is broken: ```js var es = new EventSource(request, response, { headers: {'Access-Control-Allow-Origin': '*'}, ping: 15, retry: 10 }); ``` You can send a ping message at any time by calling `es.ping()`. Unlike WebSocket, the client does not send a response to this; it is merely to send some data over the wire to keep the connection alive. ## License (The MIT License) Copyright (c) 2010-2013 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. faye-websocket-node-0.7.2/examples/000077500000000000000000000000001226001255000171625ustar00rootroot00000000000000faye-websocket-node-0.7.2/examples/autobahn_client.js000066400000000000000000000016621226001255000226640ustar00rootroot00000000000000var WebSocket = require('../lib/faye/websocket'), pace = require('pace'); var host = 'ws://localhost:9001', agent = 'Node ' + process.version, cases = 0, skip = []; var socket = new WebSocket.Client(host + '/getCaseCount'), progress; socket.onmessage = function(event) { console.log('Total cases to run: ' + event.data); cases = parseInt(event.data); progress = pace(cases); }; socket.onclose = function() { var runCase = function(n) { progress.op(); if (n > cases) { socket = new WebSocket.Client(host + '/updateReports?agent=' + encodeURIComponent(agent)); socket.onclose = process.exit; } else if (skip.indexOf(n) >= 0) { runCase(n + 1); } else { socket = new WebSocket.Client(host + '/runCase?case=' + n + '&agent=' + encodeURIComponent(agent)); socket.pipe(socket); socket.on('close', function() { runCase(n + 1) }); } }; runCase(1); }; faye-websocket-node-0.7.2/examples/client.js000066400000000000000000000012441226001255000207770ustar00rootroot00000000000000var WebSocket = require('../lib/faye/websocket'), port = process.argv[2] || 7000, secure = process.argv[3] === 'ssl', scheme = secure ? 'wss' : 'ws', url = scheme + '://localhost:' + port + '/', headers = {Origin: 'http://faye.jcoglan.com'}, ws = new WebSocket.Client(url, null, {headers: headers}); console.log('Connecting to ' + ws.url); ws.onopen = function(event) { console.log('open'); ws.send('Hello, WebSocket!'); }; ws.onmessage = function(event) { console.log('message', event.data); // ws.close(1002, 'Going away'); }; ws.onclose = function(event) { console.log('close', event.code, event.reason); }; faye-websocket-node-0.7.2/examples/haproxy.conf000066400000000000000000000005501226001255000215230ustar00rootroot00000000000000defaults mode http timeout client 5s timeout connect 5s timeout server 5s frontend all 0.0.0.0:3000 mode http timeout client 120s option forwardfor option http-server-close option http-pretend-keepalive default_backend sockets backend sockets balance uri depth 2 timeout server 120s server socket1 127.0.0.1:7000 faye-websocket-node-0.7.2/examples/server.js000066400000000000000000000035421226001255000210320ustar00rootroot00000000000000var WebSocket = require('../lib/faye/websocket'), fs = require('fs'), http = require('http'), https = require('https'); var port = process.argv[2] || 7000, secure = process.argv[3] === 'ssl'; var upgradeHandler = function(request, socket, head) { var ws = new WebSocket(request, socket, head, ['irc', 'xmpp'], {ping: 5}); console.log('open', ws.url, ws.version, ws.protocol); ws.pipe(ws); ws.onclose = function(event) { console.log('close', event.code, event.reason); ws = null; }; }; var requestHandler = function(request, response) { if (!WebSocket.EventSource.isEventSource(request)) return staticHandler(request, response); var es = new WebSocket.EventSource(request, response), time = parseInt(es.lastEventId, 10) || 0; console.log('open', es.url, es.lastEventId); var loop = setInterval(function() { time += 1; es.send('Time: ' + time); setTimeout(function() { if (es) es.send('Update!!', {event: 'update', id: time}); }, 1000); }, 2000); fs.createReadStream(__dirname + '/haproxy.conf').pipe(es, {end: false}); es.onclose = function() { clearInterval(loop); console.log('close', es.url); es = null; }; }; var staticHandler = function(request, response) { var path = request.url; fs.readFile(__dirname + path, function(err, content) { var status = err ? 404 : 200; response.writeHead(status, {'Content-Type': 'text/html'}); response.write(content || 'Not found'); response.end(); }); }; var server = secure ? https.createServer({ key: fs.readFileSync(__dirname + '/../spec/server.key'), cert: fs.readFileSync(__dirname + '/../spec/server.crt') }) : http.createServer(); server.on('request', requestHandler); server.on('upgrade', upgradeHandler); server.listen(port); faye-websocket-node-0.7.2/examples/sse.html000066400000000000000000000015261226001255000206460ustar00rootroot00000000000000 EventSource test

EventSource test

faye-websocket-node-0.7.2/examples/ws.html000066400000000000000000000022121226001255000204760ustar00rootroot00000000000000 WebSocket test

WebSocket test

faye-websocket-node-0.7.2/lib/000077500000000000000000000000001226001255000161125ustar00rootroot00000000000000faye-websocket-node-0.7.2/lib/faye/000077500000000000000000000000001226001255000170365ustar00rootroot00000000000000faye-websocket-node-0.7.2/lib/faye/eventsource.js000066400000000000000000000072621226001255000217450ustar00rootroot00000000000000var Stream = require('stream').Stream, util = require('util'), driver = require('websocket-driver'), Headers = require('websocket-driver/lib/websocket/driver/headers'), API = require('./websocket/api'), EventTarget = require('./websocket/api/event_target'), Event = require('./websocket/api/event'); var EventSource = function(request, response, options) { this.writable = true; options = options || {}; this._stream = response.socket; this._ping = options.ping || this.DEFAULT_PING; this._retry = options.retry || this.DEFAULT_RETRY; var scheme = driver.isSecureRequest(request) ? 'https:' : 'http:'; this.url = scheme + '//' + request.headers.host + request.url; this.lastEventId = request.headers['last-event-id'] || ''; this.readyState = API.CONNECTING; var headers = new Headers(), self = this; if (options.headers) { for (var key in options.headers) headers.set(key, options.headers[key]); } if (!this._stream || !this._stream.writable) return; process.nextTick(function() { self._open() }); this._stream.setTimeout(0); this._stream.setNoDelay(true); var handshake = 'HTTP/1.1 200 OK\r\n' + 'Content-Type: text/event-stream\r\n' + 'Cache-Control: no-cache, no-store\r\n' + 'Connection: close\r\n' + headers.toString() + '\r\n' + 'retry: ' + Math.floor(this._retry * 1000) + '\r\n\r\n'; this._write(handshake); this._stream.on('drain', function() { self.emit('drain') }); if (this._ping) this._pingTimer = setInterval(function() { self.ping() }, this._ping * 1000); ['error', 'end'].forEach(function(event) { self._stream.on(event, function() { self.close() }); }); }; util.inherits(EventSource, Stream); EventSource.isEventSource = function(request) { if (request.method !== 'GET') return false; var accept = (request.headers.accept || '').split(/\s*,\s*/); return accept.indexOf('text/event-stream') >= 0; }; var instance = { DEFAULT_PING: 10, DEFAULT_RETRY: 5, _write: function(chunk) { if (!this.writable) return false; try { return this._stream.write(chunk, 'utf8'); } catch (e) { return false; } }, _open: function() { if (this.readyState !== API.CONNECTING) return; this.readyState = API.OPEN; var event = new Event('open'); event.initEvent('open', false, false); this.dispatchEvent(event); }, write: function(message) { return this.send(message); }, end: function(message) { if (message !== undefined) this.write(message); this.close(); }, send: function(message, options) { if (this.readyState > API.OPEN) return false; message = String(message).replace(/(\r\n|\r|\n)/g, '$1data: '); options = options || {}; var frame = ''; if (options.event) frame += 'event: ' + options.event + '\r\n'; if (options.id) frame += 'id: ' + options.id + '\r\n'; frame += 'data: ' + message + '\r\n\r\n'; return this._write(frame); }, ping: function() { return this._write(':\r\n\r\n'); }, close: function() { if (this.readyState > API.OPEN) return false; this.readyState = API.CLOSED; this.writable = false; if (this._pingTimer) clearInterval(this._pingTimer); if (this._stream) this._stream.end(); var event = new Event('close'); event.initEvent('close', false, false); this.dispatchEvent(event); return true; } }; for (var method in instance) EventSource.prototype[method] = instance[method]; for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key]; module.exports = EventSource; faye-websocket-node-0.7.2/lib/faye/websocket.js000066400000000000000000000022201226001255000213560ustar00rootroot00000000000000// API references: // // * http://dev.w3.org/html5/websockets/ // * http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-eventtarget // * http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-event var util = require('util'), driver = require('websocket-driver'), API = require('./websocket/api'); var WebSocket = function(request, socket, body, protocols, options) { options = options || {}; this._stream = socket; this._driver = driver.http(request, {maxLength: options.maxLength, protocols: protocols}); var self = this; if (!this._stream || !this._stream.writable) return; var catchup = function() { self._stream.removeListener('data', catchup) }; this._stream.on('data', catchup); this._driver.io.write(body); API.call(this, options); process.nextTick(function() { self._driver.start(); }); }; util.inherits(WebSocket, API); WebSocket.isWebSocket = function(request) { return driver.isWebSocket(request); }; WebSocket.WebSocket = WebSocket; WebSocket.Client = require('./websocket/client'); WebSocket.EventSource = require('./eventsource'); module.exports = WebSocket; faye-websocket-node-0.7.2/lib/faye/websocket/000077500000000000000000000000001226001255000210245ustar00rootroot00000000000000faye-websocket-node-0.7.2/lib/faye/websocket/api.js000066400000000000000000000075221226001255000221410ustar00rootroot00000000000000var Stream = require('stream').Stream, util = require('util'), EventTarget = require('./api/event_target'), Event = require('./api/event'); var API = function(options) { options = options || {}; this.readable = this.writable = true; var headers = options.headers; if (headers) { for (var name in headers) this._driver.setHeader(name, headers[name]); } this._ping = options.ping; this._pingId = 0; this.readyState = API.CONNECTING; this.bufferedAmount = 0; this.protocol = ''; this.url = this._driver.url; this.version = this._driver.version; var self = this; this._stream.setTimeout(0); this._stream.setNoDelay(true); ['close', 'end'].forEach(function(event) { this._stream.on(event, function() { self._finalize('', 1006) }); }, this); this._stream.on('error', function(error) { var event = new Event('error', {message: 'Network error: ' + self.url + ': ' + error.message}); event.initEvent('error', false, false); self.dispatchEvent(event); self._finalize('', 1006); }); this._driver.on('open', function(e) { self._open() }); this._driver.on('message', function(e) { self._receiveMessage(e.data) }); this._driver.on('close', function(e) { self._finalize(e.reason, e.code) }); this._driver.on('error', function(error) { var event = new Event('error', {message: error.message}); event.initEvent('error', false, false); self.dispatchEvent(event); }); this.on('error', function() {}); this._driver.messages.on('drain', function() { self.emit('drain'); }); if (this._ping) this._pingTimer = setInterval(function() { self._pingId += 1; self.ping(self._pingId.toString()); }, this._ping * 1000); this._stream.pipe(this._driver.io); this._driver.io.pipe(this._stream); }; util.inherits(API, Stream); API.CONNECTING = 0; API.OPEN = 1; API.CLOSING = 2; API.CLOSED = 3; var instance = { write: function(data) { return this.send(data); }, end: function(data) { if (data !== undefined) this.send(data); this.close(); }, pause: function() { return this._driver.messages.pause(); }, resume: function() { return this._driver.messages.resume(); }, send: function(data) { if (this.readyState > API.OPEN) return false; if (!(data instanceof Buffer)) data = String(data); return this._driver.messages.write(data); }, ping: function(message, callback) { if (this.readyState > API.OPEN) return false; return this._driver.ping(message, callback); }, close: function() { if (this.readyState === API.OPEN) this.readyState = API.CLOSING; this._driver.close(); }, _open: function() { if (this.readyState !== API.CONNECTING) return; this.readyState = API.OPEN; this.protocol = this._driver.protocol || ''; var event = new Event('open'); event.initEvent('open', false, false); this.dispatchEvent(event); }, _receiveMessage: function(data) { if (this.readyState > API.OPEN) return false; if (this.readable) this.emit('data', data); var event = new Event('message', {data: data}); event.initEvent('message', false, false); this.dispatchEvent(event); }, _finalize: function(reason, code) { if (this.readyState === API.CLOSED) return; if (this._pingTimer) clearInterval(this._pingTimer); if (this._stream) this._stream.end(); if (this.readable) this.emit('end'); this.readable = this.writable = false; this.readyState = API.CLOSED; var event = new Event('close', {code: code || 1000, reason: reason || ''}); event.initEvent('close', false, false); this.dispatchEvent(event); } }; for (var method in instance) API.prototype[method] = instance[method]; for (var key in EventTarget) API.prototype[key] = EventTarget[key]; module.exports = API; faye-websocket-node-0.7.2/lib/faye/websocket/api/000077500000000000000000000000001226001255000215755ustar00rootroot00000000000000faye-websocket-node-0.7.2/lib/faye/websocket/api/event.js000066400000000000000000000007721226001255000232620ustar00rootroot00000000000000var Event = function(eventType, options) { this.type = eventType; for (var key in options) this[key] = options[key]; }; Event.prototype.initEvent = function(eventType, canBubble, cancelable) { this.type = eventType; this.bubbles = canBubble; this.cancelable = cancelable; }; Event.prototype.stopPropagation = function() {}; Event.prototype.preventDefault = function() {}; Event.CAPTURING_PHASE = 1; Event.AT_TARGET = 2; Event.BUBBLING_PHASE = 3; module.exports = Event; faye-websocket-node-0.7.2/lib/faye/websocket/api/event_target.js000066400000000000000000000011611226001255000246210ustar00rootroot00000000000000var Event = require('./event'); var EventTarget = { onopen: null, onmessage: null, onerror: null, onclose: null, addEventListener: function(eventType, listener, useCapture) { this.on(eventType, listener); }, removeEventListener: function(eventType, listener, useCapture) { this.removeListener(eventType, listener); }, dispatchEvent: function(event) { event.target = event.currentTarget = this; event.eventPhase = Event.AT_TARGET; if (this['on' + event.type]) this['on' + event.type](event); this.emit(event.type, event); } }; module.exports = EventTarget; faye-websocket-node-0.7.2/lib/faye/websocket/client.js000066400000000000000000000023001226001255000226330ustar00rootroot00000000000000var util = require('util'), net = require('net'), tls = require('tls'), driver = require('websocket-driver'), API = require('./api'), Event = require('./api/event'); var Client = function(url, protocols, options) { options = options || {}; this.url = url; this._uri = require('url').parse(url); this._driver = driver.client(url, {maxLength: options.maxLength, protocols: protocols}); ['open', 'error'].forEach(function(event) { this._driver.on(event, function() { self.headers = self._driver.headers; self.statusCode = self._driver.statusCode; }); }, this); var secure = (this._uri.protocol === 'wss:'), onConnect = function() { self._driver.start() }, tlsOptions = {}, self = this; if (options.ca) tlsOptions.ca = options.ca; var connection = secure ? tls.connect(this._uri.port || 443, this._uri.hostname, tlsOptions, onConnect) : net.createConnection(this._uri.port || 80, this._uri.hostname); this._stream = connection; if (!secure) this._stream.on('connect', onConnect); API.call(this, options); }; util.inherits(Client, API); module.exports = Client; faye-websocket-node-0.7.2/package.json000066400000000000000000000015071226001255000176350ustar00rootroot00000000000000{ "name" : "faye-websocket" , "description" : "Standards-compliant WebSocket server and client" , "homepage" : "http://github.com/faye/faye-websocket-node" , "author" : "James Coglan (http://jcoglan.com/)" , "keywords" : ["websocket", "eventsource"] , "license" : "MIT" , "version" : "0.7.2" , "engines" : {"node": ">=0.4.0"} , "main" : "./lib/faye/websocket" , "dependencies" : {"websocket-driver": ">=0.3.1"} , "devDependencies" : {"jstest": "", "pace": ""} , "scripts" : {"test": "jstest spec/runner.js"} , "repository" : { "type" : "git" , "url" : "git://github.com/faye/faye-websocket-node.git" } , "bugs" : "http://github.com/faye/faye-websocket-node/issues" } faye-websocket-node-0.7.2/spec/000077500000000000000000000000001226001255000162765ustar00rootroot00000000000000faye-websocket-node-0.7.2/spec/faye/000077500000000000000000000000001226001255000172225ustar00rootroot00000000000000faye-websocket-node-0.7.2/spec/faye/websocket/000077500000000000000000000000001226001255000212105ustar00rootroot00000000000000faye-websocket-node-0.7.2/spec/faye/websocket/client_spec.js000066400000000000000000000111111226001255000240310ustar00rootroot00000000000000var Client = require('../../../lib/faye/websocket/client'), test = require('jstest').Test, fs = require('fs') var WebSocketSteps = test.asyncSteps({ server: function(port, secure, callback) { this._adapter = new EchoServer() this._adapter.listen(port, secure) this._port = port process.nextTick(callback) }, stop: function(callback) { this._adapter.stop() process.nextTick(callback) }, open_socket: function(url, protocols, callback) { var done = false, self = this, resume = function(open) { if (done) return done = true self._open = open callback() } this._ws = new Client(url, protocols, { ca: fs.readFileSync(__dirname + '/../../server.crt') }) this._ws.onopen = function() { resume(true) } this._ws.onclose = function() { resume(false) } }, close_socket: function(callback) { var self = this this._ws.onclose = function() { self._open = false callback() } this._ws.close() }, check_open: function(callback) { this.assert( this._open ) callback() }, check_closed: function(callback) { this.assert( !this._open ) callback() }, check_protocol: function(protocol, callback) { this.assertEqual( protocol, this._ws.protocol ) callback() }, listen_for_message: function(callback) { var time = new Date().getTime(), self = this this._ws.addEventListener('message', function(message) { self._message = message.data }) var timer = setInterval(function() { if (self._message || new Date().getTime() - time > 3000) { clearInterval(timer) callback() } }, 100) }, send_message: function(message, callback) { var ws = this._ws setTimeout(function() { ws.send(message) }, 500) process.nextTick(callback) }, check_response: function(message, callback) { this.assertEqual( message, this._message ) callback() }, check_no_response: function(callback) { this.assert( !this._message ) callback() } }) test.describe("Client", function() { with(this) { include(WebSocketSteps) before(function() { this.protocols = ["foo", "echo"] this.plain_text_url = "ws://localhost:4180/bayeux" this.secure_url = "wss://localhost:4180/bayeux" this.port = 4180 }) sharedBehavior("socket client", function() { with(this) { it("can open a connection", function() { with(this) { open_socket(socket_url, protocols) check_open() check_protocol("echo") }}) it("can close the connection", function() { with(this) { open_socket(socket_url, protocols) close_socket() check_closed() }}) describe("in the OPEN state", function() { with(this) { before(function() { with(this) { open_socket(socket_url, protocols) }}) it("can send and receive messages", function() { with(this) { send_message("I expect this to be echoed") listen_for_message() check_response("I expect this to be echoed") }}) it("sends numbers as strings", function() { with(this) { send_message(13) listen_for_message() check_response("13") }}) it("sends booleans as strings", function() { with(this) { send_message(false) listen_for_message() check_response("false") }}) it("sends arrays as strings", function() { with(this) { send_message([13,14,15]) listen_for_message() check_response("13,14,15") }}) }}) describe("in the CLOSED state", function() { with(this) { before(function() { with(this) { open_socket(socket_url, protocols) close_socket() }}) it("cannot send and receive messages", function() { with(this) { send_message("I expect this to be echoed") listen_for_message() check_no_response() }}) }}) }}) describe("with a plain-text server", function() { with(this) { before(function() { this.socket_url = this.plain_text_url this.blocked_url = this.secure_url }) before(function() { this.server(4180, false) }) after (function() { this.stop() }) behavesLike("socket client") }}) describe("with a secure server", function() { with(this) { before(function() { this.socket_url = this.secure_url this.blocked_url = this.plain_text_url }) before(function() { this.server(4180, true) }) after (function() { this.stop() }) behavesLike("socket client") }}) }}) faye-websocket-node-0.7.2/spec/runner.js000066400000000000000000000016271226001255000201530ustar00rootroot00000000000000var WebSocket = require('../lib/faye/websocket'), fs = require('fs'), http = require('http'), https = require('https'), test = require('jstest').Test EchoServer = function() {} EchoServer.prototype.listen = function(port, ssl) { var server = ssl ? https.createServer({ key: fs.readFileSync(__dirname + '/server.key'), cert: fs.readFileSync(__dirname + '/server.crt') }) : http.createServer() server.on('upgrade', function(request, socket, head) { var ws = new WebSocket(request, socket, head, ["echo"]) ws.pipe(ws) }) this._httpServer = server server.listen(port) } EchoServer.prototype.stop = function(callback, scope) { this._httpServer.on('close', function() { if (callback) callback.call(scope); }); this._httpServer.close(); } require('./faye/websocket/client_spec') faye-websocket-node-0.7.2/spec/server.crt000066400000000000000000000014521226001255000203200ustar00rootroot00000000000000-----BEGIN CERTIFICATE----- MIICKTCCAZICCQDtAJo/efrTvjANBgkqhkiG9w0BAQUFADBZMQswCQYDVQQGEwJV SzETMBEGA1UECBMKU29tZS1TdGF0ZTEPMA0GA1UEBxMGTG9uZG9uMRAwDgYDVQQK EwdqY29nbGFuMRIwEAYDVQQDEwlsb2NhbGhvc3QwHhcNMTMwNjE5MDcwNzQ1WhcN MTQwNjE5MDcwNzQ1WjBZMQswCQYDVQQGEwJVSzETMBEGA1UECBMKU29tZS1TdGF0 ZTEPMA0GA1UEBxMGTG9uZG9uMRAwDgYDVQQKEwdqY29nbGFuMRIwEAYDVQQDEwls b2NhbGhvc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALhPVRbctfcjCJEC DsZfgtTMVYMsvV/miLxc7veumuuApe5y3DFuG8Tlz3/0wrvRm3dCSUOfIBK8ktor VoY6QGHwrhYK2MhnJQOUTYC+FCyUp4zAYjRgJWd4uTii+uqRbLCPOF8jEx7VunTT Lj9hu82IdRgT3OtqzPUoTmYXCXSZAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAcARo TO7LTbII0HIsB7PePspFkwiuYQtvFqYm10I+4yuIdfPBdH0/OBhKvNC1O7tc7dmy NPd8e5FXrt6qHDgCVh0kpg37sMJp42jUCn4lguWKN5dZPkzGrRFUfXvcx1qwdF2T 0CgyULvKWl9wt3Wp5feG8dNn1UZOGlZBZ+0GNyk= -----END CERTIFICATE----- faye-websocket-node-0.7.2/spec/server.key000066400000000000000000000015671226001255000203270ustar00rootroot00000000000000-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQC4T1UW3LX3IwiRAg7GX4LUzFWDLL1f5oi8XO73rprrgKXuctwx bhvE5c9/9MK70Zt3QklDnyASvJLaK1aGOkBh8K4WCtjIZyUDlE2AvhQslKeMwGI0 YCVneLk4ovrqkWywjzhfIxMe1bp00y4/YbvNiHUYE9zrasz1KE5mFwl0mQIDAQAB AoGAfcTc6oHnxeHpKZJ+5I0uaOmafK2d+IAG1IqSIv/KBWQ/VoyYhz58woqTYtxx udqZvPLFrdg6+a4mg6vJGkVLwp/PFi7r57/vqUR/P8SnuV0iTJZ7BczZHSffdzgT 9v2XUDFZ3ZSjIi+XkCMirHc7G8BVYImqjCGy80NX3YB5RRECQQDuX+udSSZi2I0C gT/LnoVsb8JkanNALZH/U/XQog50I9aNf2GAAboUVsGuETL3I9f12Ku0A+xK5biv s4P4g01FAkEAxfALp1Yzud+ooNmbbtSTE6hrUwjFeG1skEW4GvocB5ZiQqXwv59v AmWedup7St2kamb5vNtcpewHGd2kUpatRQJARDwg7f0qh9EFTFpDML5H4yp6stPl +dERoc0e6IH7MTOxDwAPoNzdr0TGXFWACU6xWyaSwAz/btEjdOgmNtUfIQJAFrWO sLksIBQwBZxRv+p1oVi+T31/Imzzeq31DGtLkfdH+LuPHn0NQGomPyBx2soJFggQ eQF15LdqrSYHt04APQJBAO2SPMC7MxDKdhryf6PDcaL/lTKSxRttQ72jZmDU9ujp dcvFPgrQTa3iNLm4SWvARFXXZrrGEeDgKX7jVJygfI4= -----END RSA PRIVATE KEY-----