eva-events
v0.4.0
Published
Eva is like an EventEmitter, but over WebSockets.
Downloads
4
Maintainers
Readme
eva-events
Eva is like an EventEmitter, but over WebSockets.
Features
- Bidirectional
EventEmitter
over WebSockets - Very high performance (and memory efficient)
- Messages can be between 10–60% smaller than JSON
- You can send
Date
,Error
,Buffer
,RegExp
,ArrayBuffer
,TypedArray
,Infinity
,NaN
, and of course everything that you can normally send with JSON. Magic! - Only 38 kB minified and gzipped
- If you're already using bluebird (22 kB), and browserify's Buffer and EventEmitter (8 kB), then
eva-events
weighs in at only 8 kB extra
Basic usage
Client:
var Eva = require('eva-events');
var eva = new Eva('ws://myapp.com');
eva.on('greeting', function (msg) {
console.log(msg); // "Hello world!";
});
Server:
var EvaApp = require('eva-events').Application;
var app = EvaApp(server);
app.on('client', function (eva) {
eva.emit('greeting', 'Hello world!');
});
Explanation
On the client, .emit()
triggers an event on the server. On the server, .emit()
triggers an event on the client.
Aside, from the .emit()
method, you can also use the .run()
method, which returns a promise which is fulfilled with the return value of the remote event listener. If an Error
object is returned, the promise is rejected with that error.
Special reserved events
There are four special events you cannot .emit()
:
ready
done
killed
error
The ready
event is triggered on a client when an open connection has been established and events may be sent back and forth.
The done
event is triggered when the connection starts closing. After this event, neither party may emit new events. The connection will gracefully wait for pending transactions to finish before closing completely (unless there's an error or the connection is killed before then).
The killed
event is triggered when the underlying connection has been completed closed. The first argument of this event is a boolean indicating if the connection was closed cleanly.
The error
event is triggered when a fatal error occurs. This event will always kill the connection immediately after. This cannot be prevented. The first argument of this event is the associated error
object.
Note:
You cannot emit or listen to the newListener
or removeListener
events. Doing so will throw a SyntaxError
.
Caution when using .run()
If you .run()
an event before the other endpoint has registered a listener for that event, eva
will wait for a response indefinitely. Other things can cause transactions to wait indefinitely too, such as poorly written application code. To prevent this, you can use .timeout()
which causes all new .run()
transactions to fail and kill the connection if they aren't settled after a certain amount of time. You should always listen on the killed
event to react to these things accordingly.
Browser compatibility
Much of Eva
's awesomeness comes from her apt use of modern web technologies. She requires the Map
object, and WebSocket
with binary support (no legacy versions, only RFC-6455).
Natively, this package is supported by:
- Chrome 38+
- Firefox 13+
- Safari 7.1+
- Opera 25+
- Internet Exporer 11+
- Edge
However, if you polyfill Map
you can support:
- Chrome 16+
- Firefox 11+
- Safari 7+
- Opera 12.1+
- Internet Exporer 10+
- Edge
API Reference
Class: Eva
On the client, these instances can be created by invoking the constructor:
var Eva = require('eva-events')
var eva = new Eva('ws://myapp.com/path/to/app')
On the server, these instances are exposed by EvaApplication in the client
event.
.kill() -> this
Kills the connection. The done
event is immediately emitted. All pending transactions are discarded. It may take some time for the underlying connection to actually close, so when it does, the killed
event is emitted.
.done() -> this
Starts to gracefully end the connection. The done
event is immediately emitted. Both endpoints will then wait for all pending transactions to be resolved before finally closing the underlying connection (at which point, the killed
event is emitted).
.emit(string eventName, [any data]) -> this
This emits an event to the opposite endpoint. Remote event listeners are invoked with data as the first argument.
.run(string eventName, [any data]) -> Promise
This is the same as .emit()
, except instead of just emitting an event, it starts a transaction. Only the first event listener for the event will fired, and that listener's return value is sent back and made available as the fulfillment value of the promise returned by this method. Or, if the return value is an Error
object, the promise is rejected with it. Promises returned by this method, and promises chained from that promise, have a this
value of the eva
instance. Event listeners can return promises, whose fulfillment values or rejection reasons will be made available as the fulfillment value or rejection reason of the promise returned by this method.
.on(string eventName, function listener) -> this
.addListener(string eventName, function listener) -> this
Registers an event listener listener for event eventName.
.once(string eventName, function listener) -> this
Same as .on()
, but the listener will only be invoked once.
.removeListener(string eventName, function listener) -> this
Unregisters a listener listener that has been registered with event eventName.
.listenerCount(string eventName) -> number
Returns the number of event listeners that are registered with event eventName.
.timeout(number sec) -> this
Causes all future transactions (started by the .run()
method) to timeout after sec seconds, at which point an error
event will be emitted and the connection will be forcefully killed. A sec value of 0
or Infinity
turns off timeouts.
Default: 0
.killTimeout(number sec) -> this
Sets how long eva
will wait to gracefully end the connection, before timing out and forcefully killing it. A sec value of 0
or Infinity
indicates that eva
will wait forever.
Default: 30
get .isReady -> boolean
Indicates if the connection is open and events may be sent back and forth.
get .bufferedAmount -> number
Returns the number of bytes in the internal buffer. In advanced applications, this can be monitered to adjust network usage rates.
Class: EvaApplication
On the server only:
var EvaApp = require('eva-events').Application
var app = EvaApp(server, '/path/to/app', options)
constructor EvaApplication(http.Server server, [string path], [Object options])
path defaults to "/"
EvaApplication
is an EventEmitter
. When a new client connects, the client
event is emitted with the Eva
client as the first argument. If the EvaApplication
is locked
, and there are no more clients connected, the vacant
event is fired.
Options
options.verifyClients
You may supply a verifyClients function which must return true
for each client wishing to connect to the WebSocket endpoint. The function may have the following two signatures:
function verifyClients(info) { // synchronous
return false
}
function verifyClients(info, cb) { // asynchronous
cb(false, 401, 'Unauthorized')
}
info is an object with the following properties:
- string origin
- boolean secure
- http.IncomingMessage req
options.useHeartbeat
By default, all clients of an EvaApplication
will periodically be sent a heartbeat. If a client endpoint does not respond after 10 heartbeats, the connection will be destroyed. Setting options.useHeartbeat = false
will cause this instance of EvaApplication
to not send and track heartbeats.
.lock() -> this
Prevents new clients from connecting to the websocket endpoint.
.unlock() -> this
Allows new clients to connect to the websocket endpoint. When an EvaApplication
instance is created, it starts out unlocked.
.kill() -> this
Locks
the EvaApplication
, and invokes the .kill()
method on each connected client.
.done() -> this
Locks
the EvaApplication
, and invokes the .done()
method on each connected client.
.broadcast(string eventName, [any data]) -> this
Invokes the .emit()
method on each client that isReady
.
.currentClients() -> Array
Returns a snapshot array of the current clients that are connected.
get .isLocked -> boolean
Returns whether the EvaApplication
is currently rejecting new clients.