ws-nats
A browser websocket client library for NATS
Install
npm install --save ws-nats
Usage
Basic Example
// var NATS = window.NATS;var NATS = ; var nats = NATS; // Simple Publishernats; // Simple Subscribernats; // "*" matches any token, at any level of the subject.nats; nats; // Using Wildcard Subscriptions // ">" matches any length of the tail of a subject, and can only be// the last token E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz',// 'foo.foo.bar.bax.22'nats; // Unsubscribingvar sid = nats;nats; // Request Streamsvar sid = nats; // Request with Auto-Unsubscribe. Will unsubscribe after// the first response is received via {'max':1}nats; // Request for single response with timeout.nats; // Repliesnats;
This library is compatible with all the API methods in node-nats
Testing
To test ws-nats
, you need to connect to a NATS server using a Websocket-to-TCP relay such as nats-relay or ws-tcp-relay.
You can use Docker to run the gnatsd
server and the Websockets to TCP relay:
# launch the gnatsd server
docker run -it --name=nats --rm -d -p 4222:4222 -p 8222:8222 nats -D -m 8222
# launch the relay (assumes we are using Linux!)
docker run -it --name=relay --rm -d -p 8080:8080 aaguilar/nats-relay -p 8080 $(hostname -i):4222
# then configure ws-nats to connect to the relay
var nats = NATS.connect({ url: 'ws://0.0.0.0:8080', json: true });
Browser support
Tested in the following browsers versions:
- Google Chrome 53+
- Firefox 37+
- Internet Explorer 11
- Microsoft Edge 12+
- Safari 9+
- Mobile Safari 11+
- Opera 46+
Limitations
- TLS connections to NATS server are not supported because we are using Websocket as transport
- The
nkeys
public-key signature system has been disabled from the codebase to reduce bundle size (we plan to port this at a later stage) - The size of the library bundle has increased because we are using sockjs-client, we will remove this dependency in future releases.
Acknowledgements
This library is heavily inspired by websocket-nats and re-uses the sames API methods from the original node-nats library.