SocketCluster

next

AGServer

Inherits from

AsyncStreamEmitter

Properties

exchange A client which lets you interact with pub/sub channels and make RPC requests from the server side. (See API section on the AGExchange object for details).
clients An object which holds all fully connected clients on the current server (only those which have completed the handshake). Keys are socket IDs and the values are AGServerSocket instances.
clientsCount The number of clients currently connected to this server.
pendingClients An object which holds all pending clients on the current server. Keys are socket IDs and the values are AGServerSocket instances. Pending clients are those whose socket.state is 'connecting'; this means all sockets which are in the middle of the handshake phase. Once a socket completes its handshake, it will be removed from the pendingClients object and it will be added to the clients object.
pendingClientsCount The number of pending clients currently connected to this server.
sourcePort The public port on which clients connect to SocketCluster (e.g. 80 for HTTP).
httpServer An instance of the Node.js HTTP server to which this SC server is attached.
secure Whether or not this server uses SSL
host The host name for this server
ackTimeout The timeout in milliseconds in which clients have to receive a response to events which require acknowledgement. For example, when you call socket.invoke(...) or socket.invokePublish(...) on the client.

Events

'error' This gets triggered when fatal error occurs on this server. The object produced by the listener will have an error property.
'warning' A warning is a non-fatal error which does not require restarting the server. AGServerSocket errors are emitted as warnings on the AGServer instance. The object produced by the listener will have a warning property.
'handshake' Emitted as soon as a new AGServerSocket object is created on the server - This occurs at the beginning of the client handshake, before the 'connection' event. You should not try to send events to the socket while it is in this state. The object produced by the listener will have a socket property.
'connectionAbort' Emitted whenever a socket becomes disconnected during the handshake phase. The object produced by the listener will have a socket, code and reason property.
'connection' Emitted whenever a new socket connection is established with the server (and the handshake has completed). The object produced by the listener will have a socket, id, pingTimeout and isAuthenticated property. If an authentication error occured during the socket handshake phase, the event object will also have an authError property. The socket object of type AGServerSocket and can be used to interact with the corresponding client.
'disconnection' Emitted whenever a connected socket becomes disconnected (after the handshake phase). Note that if the socket connection was not fully established (e.g. during the SocketCluster handshake phase), then the 'connectionAbort' event will be triggered instead. The object produced by the listener will have a socket, code and reason property.
'closure' Emitted whenever a connected socket becomes disconnected (at any stage of the handshake/connection cycle). Note that this event is a catch-all for both 'disconnection' and 'connectionAbort' events. The object produced by the listener will have a socket, code and reason property.
'subscription' Emitted whenever a socket connection which is attached to the server becomes subscribed to a channel. The object produced by the listener will have a socket (AGServerSocket), a channel and channelOptions property.
'unsubscription' Emitted whenever a socket connection which is attached to the server becomes unsubscribed from a channel. The object produced by the listener will have a socket and channel property.
'authentication' Emitted whenever a socket connection which is attached to the server becomes authenticated. The object produced by the listener will have a socket and authToken property.
'deauthentication' Emitted whenever a socket connection which is attached to the server becomes deauthenticated. The object produced by the listener will have a socket and oldAuthToken property.
'authenticationStateChange' Triggers whenever the authState of a socket which is attached to the server changes (e.g. transitions between authenticated and unauthenticated states). The object produced by the listener will have a socket, oldAuthState and newAuthState property.
'badSocketAuthToken' Emitted when a client which is attached to the server tries to authenticate itself with an invalid (or expired) token. The object produced by the listener will have a socket, authError and signedAuthToken property.
'ready' Emitted when the server is ready to accept connections.

Methods

constructor(options)

Create the server instance (with config options). Note that you can also create the server using the attach method of the top-level socketClusterServer instance. The options object can have any of the following properties (sample showing defaults):

{
// An instance of a Node.js HTTP server.
// https://nodejs.org/api/http.html#http_class_http_server
// This option should not be set if the server is created
// with socketClusterServer.attach(...).
httpServer: null,
// This can be the name of an npm module or a path to a
// Node.js module to use as the WebSocket server engine.
wsEngine: 'ws',
// Custom options to pass to the wsEngine when it is being
// instantiated.
wsEngineServerOptions: {},
// The key which SC will use to encrypt/decrypt authTokens,
// defaults to a 256 bits cryptographically random hex
// string. The default JWT algorithm used is 'HS256'.
// If you want to use RSA or ECDSA, you should provide an
// authPrivateKey and authPublicKey instead of authKey.
authKey: null,
// perMessageDeflate compression. Note that this option is
// passed directly to the wsEngine's Server object.
// So if you're using 'ws' as the engine, you can pass an
// object instead of a boolean.
// Note that by default, per-message deflate only kicks in
// for messages > 1024 bytes.
perMessageDeflate: false,
// If using an RSA or ECDSA algorithm to sign the
// authToken, you will need to provide an authPrivateKey
// and authPublicKey in PEM format (string or Buffer).
authPrivateKey: null,
authPublicKey: null,
// The default expiry for auth tokens in seconds
authDefaultExpiry: 86400,
// The algorithm to use to sign and verify JWT tokens.
authAlgorithm: 'HS256',
// Can be 1 or 2. Version 1 is for maximum backwards
// compatibility with SocketCluster clients.
protocolVersion: 2,
// In milliseconds - If the socket handshake hasn't been
// completed before this timeout is reached, the new
// connection attempt will be terminated.
handshakeTimeout: 10000,
// In milliseconds, the timeout for receiving a response
// when using invoke() or invokePublish().
ackTimeout: 10000,
// Origins which are allowed to connect to the server.
origins: '*:*',
// The maximum number of unique channels which a single
// socket can subscribe to.
socketChannelLimit: 1000,
// The interval in milliseconds on which to
// send a ping to the client to check that
// it is still alive.
pingInterval: 8000,
// How many milliseconds to wait without receiving a ping
// before closing the socket.
pingTimeout: 20000,
// Whether or not an error should be emitted on
// the socket whenever an action is blocked by a
// middleware function
middlewareEmitFailures: true,
// The URL path reserved by SocketCluster clients to
// interact with the server.
path: '/socketcluster/',
// Whether or not clients are allowed to publish messages
// to channels.
allowClientPublish: true,
// Whether or not to batch all socket messages
// for some time immediately after completing
// a handshake. This can be useful in failure-recovery
// scenarios (e.g. batch resubscribe).
batchOnHandshake: false,
// If batchOnHandshake is true, this lets you specify
// How long to enable batching (in milliseconds) following
// a successful socket handshake.
batchOnHandshakeDuration: 400,
// If batchOnHandshake is true, this lets you specify
// the size of each batch in milliseconds.
batchInterval: 50,
// Lets you specify the default cleanup behaviour for
// when a socket becomes disconnected.
// Can be either 'kill' or 'close'. Kill mode means
// that all of the socket's streams will be killed and
// so consumption will stop immediately.
// Close mode means that consumers on the socket will
// be able to finish processing their stream backlogs
// bebfore they are ended.
socketStreamCleanupMode: 'kill'
}
close()

Close the server and terminate all sockets.

setMiddleware(type, middlewareFn) Lets you set a middleware functions which can be used to manage client access control to various features of the AGServer. This is useful for monitoring real-time data flows and also to block access to restricted channels and resources. Note that only actions from clients pass through middleware. Server side calls on the AGExchange client such as agServer.exchange.transmitPublish(...) or agServer.exchange.invokePublish(...) do not. See Middleware and authorization guide for a list of all available middleware types and actions.
removeMiddleware(type, middlewareFn)

Lets you remove a middleware function which was previously added using the setMiddleware(...) method.

listener(eventName)

This method returns an event listener stream for the specified eventName. This object is an asyncIterable which can be consumed with a for-await-of loop.

See basic usage guide for examples of how to consume listener streams. For more advanced usage, see StreamDemux (this is the library which SocketCluster uses to implement listener streams).

closeListener(eventName) This method will signal to all consuming for-await-of loops (for the eventName listener) to break after they have finished iterating over their current backlogs of events.
closeAllListeners() This method will signal to all consuming for-await-of loops for all listeners to break after they have finished consuming their respective backlogs of events.
killListener(eventName) This method will signal to all consuming for-await-of loops for the eventName listener to break immediately and will reset the backpressure for that listener to 0.
killAllListeners() This method will signal to all consuming for-await-of loops for all listeners to break immediately and will reset the aggregate backpressure for all listeners to 0.
getAllListenersBackpressure() Returns the aggregate backpressure for the server's event listener streams.
getListenerBackpressure(eventName) Get the aggregate backpressure for the eventName listener stream on the server instance. The aggregate backpressure represents the highest backpressure of all consumers for that listener.

Stream management methods

These methods should only be used for advanced use cases when you need more control over stream management; for example, when you want to break out of a specific consumer loop without affecting any other consumer. These methods can also be useful to check that consumers are being cleaned up properly and to selectively kill specific consumers which are causing backpressure to build up. For most use cases, you should try to stick to the methods in the table above as it will lead to cleaner logic.

getListenerConsumerStatsList(eventName) Get the list of consumers which are consuming data from the specified event listener. This method returns a list of objects which have an id and backpressure property.
getAllListenersConsumerStatsList() Get the list of all consumers which are consuming data from any listener on the server. This method returns a list of objects which have an id and backpressure property.
killListenerConsumer(consumerId) This will cause the target listener consumer's for-await-of loop to break immediately.

AltStyle によって変換されたページ (->オリジナル) /