meteor/faye-websocket-node

Name: faye-websocket-node

Owner: Meteor

Description: Standards-compliant WebSocket client and server

Created: 2014-08-15 17:53:30.0

Updated: 2015-10-11 14:58:38.0

Pushed: 2014-11-11 00:48:01.0

Homepage:

Size: 396

Language: null

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

faye-websocket

This is a general-purpose WebSocket implementation extracted from the Faye 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 application. It does not provide any abstraction other than the standard WebSocket API.

It also provides an abstraction for handling 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
m 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:

WebSocket = require('faye-websocket'),
http      = require('http');

server = http.createServer();

er.on('upgrade', function(request, socket, body) {
 (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;
});



er.listen(8000);

WebSocket objects are also duplex streams, so you could replace the ws.on('message', ...) line with:

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.

ing('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.

WebSocket = require('faye-websocket'),
ws        = new WebSocket.Client('ws://www.example.com/');

n('open', function(event) {
nsole.log('open');
.send('Hello, world!');


n('message', function(event) {
nsole.log('message', event.data);


n('close', function(event) {
nsole.log('close', event.code, event.reason);
 = 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:

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:

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:

ws = new WebSocket(request, socket, body, protocols, options);
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:

WebSocket API

Both server- and client-side WebSocket objects support the following API.

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.

WebSocket   = require('faye-websocket'),
EventSource = WebSocket.EventSource,
http        = require('http');

server = http.createServer();

er.on('request', function(request, response) {
 (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');



er.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:

end('Breaking News!', {event: 'notification', id: '99'});

The EventSource object exposes the following properties:

When you initialize an EventSource with new EventSource(), you can pass configuration options after the response parameter. Available options are:

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:

es = new EventSource(request, response, {
aders: {'Access-Control-Allow-Origin': '*'},
ng:    15,
try:   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.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.