Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Generic extension management for WebSocket connections

License

NotificationsYou must be signed in to change notification settings

faye/websocket-extensions-node

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

58 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A minimal framework that supports the implementation of WebSocket extensions ina way that's decoupled from the main protocol. This library aims to allow aWebSocket extension to be written and used with any protocol library, bydefining abstract representations of frames and messages that allow modules toco-operate.

websocket-extensions provides a container for registering extension plugins,and provides all the functions required to negotiate which extensions to useduring a session via theSec-WebSocket-Extensions header. By implementing theAPIs defined in this document, an extension may be used by any WebSocket librarybased on this framework.

Installation

$ npm install websocket-extensions

Usage

There are two main audiences for this library: authors implementing theWebSocket protocol, and authors implementing extensions. End users of aWebSocket library or an extension should be able to use any extension by passingit as an argument to their chosen protocol library, without needing to know howeither of them work, or how thewebsocket-extensions framework operates.

The library is designed with the aim that any protocol implementation and anyextension can be used together, so long as they support the same abstractrepresentation of frames and messages.

Data types

The APIs provided by the framework rely on two data types; extensions willexpect to be given data and to be able to return data in these formats:

Frame

Frame is a structure representing a single WebSocket frame of any type. Framesare simple objects that must have at least the following properties, whichrepresent the data encoded in the frame:

propertydescription
finaltrue if theFIN bit is set,false otherwise
rsv1true if theRSV1 bit is set,false otherwise
rsv2true if theRSV2 bit is set,false otherwise
rsv3true if theRSV3 bit is set,false otherwise
opcodethe numeric opcode (0,1,2,8,9, or10) of the frame
maskedtrue if theMASK bit is set,false otherwise
maskingKeya 4-byteBuffer ifmasked istrue, otherwisenull
payloadaBuffer containing the (unmasked) application data

Message

AMessage represents a complete application message, which can be formed fromtext, binary and continuation frames. It has the following properties:

propertydescription
rsv1true if the first frame of the message has theRSV1 bit set
rsv2true if the first frame of the message has theRSV2 bit set
rsv3true if the first frame of the message has theRSV3 bit set
opcodethe numeric opcode (1 or2) of the first frame of the message
datathe concatenation of all the frame payloads in the message

For driver authors

A driver author is someone implementing the WebSocket protocol proper, and whowishes end users to be able to use WebSocket extensions with their library.

At the start of a WebSocket session, on both the client and the server side,they should begin by creating an extension container and adding whicheverextensions they want to use.

varExtensions=require('websocket-extensions'),deflate=require('permessage-deflate');varexts=newExtensions();exts.add(deflate);

In the following examples,exts refers to thisExtensions instance.

Client sessions

Clients will use the methodsgenerateOffer() andactivate(header).

As part of the handshake process, the client must send aSec-WebSocket-Extensions header to advertise that it supports the registeredextensions. This header should be generated using:

request.headers['sec-websocket-extensions']=exts.generateOffer();

This returns a string, for example"permessage-deflate; client_max_window_bits", that represents all the extensions the client isoffering to use, and their parameters. This string may contain multiple offersfor the same extension.

When the client receives the handshake response from the server, it should passthe incomingSec-WebSocket-Extensions header in toexts to activate theextensions the server has accepted:

exts.activate(response.headers['sec-websocket-extensions']);

If the server has sent any extension responses that the client does notrecognize, or are in conflict with one another for use of RSV bits, or that useinvalid parameters for the named extensions, thenexts.activate() willthrow. In this event, the client driver should fail the connection withclosing code1010.

Server sessions

Servers will use the methodgenerateResponse(header).

A server session needs to generate aSec-WebSocket-Extensions header to sendin its handshake response:

varclientOffer=request.headers['sec-websocket-extensions'],extResponse=exts.generateResponse(clientOffer);response.headers['sec-websocket-extensions']=extResponse;

Callingexts.generateResponse(header) activates those extensions the clienthas asked to use, if they are registered, asks each extension for a set ofresponse parameters, and returns a string containing the response parameters forall accepted extensions.

In both directions

Both clients and servers will use the methodsvalidFrameRsv(frame),processIncomingMessage(message) andprocessOutgoingMessage(message).

The WebSocket protocol requires that frames do not have any of theRSV bitsset unless there is an extension in use that allows otherwise. When processingan incoming frame, sessions should pass aFrame object to:

exts.validFrameRsv(frame)

If this method returnsfalse, the session should fail the WebSocket connectionwith closing code1002.

To pass incoming messages through the extension stack, a session shouldconstruct aMessage object according to the above datatype definitions, andcall:

exts.processIncomingMessage(message,function(error,msg){// hand the message off to the application});

If any extensions fail to process the message, then the callback will yield anerror and the session should fail the WebSocket connection with closing code1010. Iferror isnull, thenmsg should be passed on to the application.

To pass outgoing messages through the extension stack, a session shouldconstruct aMessage as before, and call:

exts.processOutgoingMessage(message,function(error,msg){// write message to the transport});

If any extensions fail to process the message, then the callback will yield anerror and the session should fail the WebSocket connection with closing code1010. Iferror isnull, thenmessage should be converted into frames(with the message'srsv1,rsv2,rsv3 andopcode set on the first frame)and written to the transport.

At the end of the WebSocket session (either when the protocol is explicitlyended or the transport connection disconnects), the driver should call:

exts.close(function(){})

The callback is invoked when all extensions have finished processing anymessages in the pipeline and it's safe to close the socket.

For extension authors

An extension author is someone implementing an extension that transformsWebSocket messages passing between the client and server. They would like toimplement their extension once and have it work with any protocol library.

Extension authors will not installwebsocket-extensions or call it directly.Instead, they should implement the following API to allow their extension toplug into thewebsocket-extensions framework.

AnExtension is any object that has the following properties:

propertydescription
namea string containing the name of the extension as used in negotiation headers
typea string, must be"permessage"
rsv1eithertrue if the extension uses the RSV1 bit,false otherwise
rsv2eithertrue if the extension uses the RSV2 bit,false otherwise
rsv3eithertrue if the extension uses the RSV3 bit,false otherwise

It must also implement the following methods:

ext.createClientSession()

This returns aClientSession, whose interface is defined below.

ext.createServerSession(offers)

This takes an array of offer params and returns aServerSession, whoseinterface is defined below. For example, if the client handshake contains theoffer header:

Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; server_max_window_bits=8, \                          permessage-deflate; server_max_window_bits=15

then thepermessage-deflate extension will receive the call:

ext.createServerSession([{server_no_context_takeover:true,server_max_window_bits:8},{server_max_window_bits:15}]);

The extension must decide which set of parameters it wants to accept, if any,and return aServerSession if it wants to accept the parameters andnullotherwise.

ClientSession

AClientSession is the type returned byext.createClientSession(). It mustimplement the following methods, as well as theSession API listed below.

clientSession.generateOffer()// e.g.  -> [//            { server_no_context_takeover: true, server_max_window_bits: 8 },//            { server_max_window_bits: 15 }//          ]

This must return a set of parameters to include in the client'sSec-WebSocket-Extensions offer header. If the session wants to offer multipleconfigurations, it can return an array of sets of parameters as shown above.

clientSession.activate(params)// -> true

This must take a single set of parameters from the server's handshake responseand use them to configure the client session. If the client accepts the givenparameters, then this method must returntrue. If it returns any other value,the framework will interpret this as the client rejecting the response, and willthrow.

ServerSession

AServerSession is the type returned byext.createServerSession(offers). Itmust implement the following methods, as well as theSession API listed below.

serverSession.generateResponse()// e.g.  -> { server_max_window_bits: 8 }

This returns the set of parameters the server session wants to send in itsSec-WebSocket-Extensions response header. Only one set of parameters isreturned to the client per extension. Server sessions that would confict ontheir use of RSV bits are not activated.

Session

TheSession API must be implemented by both client and server sessions. Itcontains two methods,processIncomingMessage(message) andprocessOutgoingMessage(message).

session.processIncomingMessage(message,function(error,msg){ ...})

The session must implement this method to take an incomingMessage as definedabove, transform it in any way it needs, then return it via the callback. Ifthere is an error processing the message, this method should yield an error asthe first argument.

session.processOutgoingMessage(message,function(error,msg){ ...})

The session must implement this method to take an outgoingMessage as definedabove, transform it in any way it needs, then return it via the callback. Ifthere is an error processing the message, this method should yield an error asthe first argument.

Note that bothprocessIncomingMessage() andprocessOutgoingMessage() canperform their logic asynchronously, are allowed to process multiple messagesconcurrently, and are not required to complete working on messages in the sameorder the messages arrive.websocket-extensions will reorder messages as yourextension emits them and will make sure every extension is given messages in theorder they arrive from the driver. This allows extensions to maintain state thatdepends on the messages' wire order, for example keeping a DEFLATE compressioncontext between messages.

session.close()

The framework will call this method when the WebSocket session ends, allowingthe session to release any resources it's using.

Examples

About

Generic extension management for WebSocket connections

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2026 Movatter.jp