Code Monkey home page Code Monkey logo

websocket-nats's Introduction

websocket-nats

npm License MIT

An in-browser websocket client for NATS, a lightweight, high-performance cloud native messaging system.

Installation

NPM

npm install websocket-nats

CDN

Normal, development, and minified versions of the bundle can obtained via RawGit.

<script type="text/javascript" src="https://cdn.rawgit.com/isobit/websocket-nats/master/dist/websocket-nats.js"></script>

Development (includes eval sourcemaps):

<script type="text/javascript" src="https://cdn.rawgit.com/isobit/websocket-nats/master/dist/websocket-nats.dev.js"></script>

Minified (for production use):

<script type="text/javascript" src="https://cdn.rawgit.com/isobit/websocket-nats/master/dist/websocket-nats.min.js"></script>

Prerequisites

You will need a Websocket-to-TCP proxy to connect to your gnatsd instance over websockets. You may provide your own or use ws-tcp-relay.

Basic Usage

Usage is the same as node-nats, but a url to your websocket/TCP proxy should be provided instead of one pointing directly at your gnatsd instance.

var nats = require('websocket-nats').connect('ws://localhost:4223');

// Simple Publisher
nats.publish('foo', 'Hello World!');

// Simple Subscriber
nats.subscribe('foo', function(msg) {
  console.log('Received a message: ' + msg);
});

// Unsubscribing
var sid = nats.subscribe('foo', function(msg) {});
nats.unsubscribe(sid);

// Request Streams
var sid = nats.request('request', function(response) {
  console.log('Got a response in msg stream: ' + response);
});

// Request with Auto-Unsubscribe. Will unsubscribe after
// the first response is received via {'max':1}
nats.request('help', null, {'max':1}, function(response) {
  console.log('Got a response for help: ' + response);
});

// Replies
nats.subscribe('help', function(request, replyTo) {
  nats.publish(replyTo, 'I can help!');
});

// Close connection
nats.close();

Wildcard Subscriptions

// "*" matches any token, at any level of the subject.
nats.subscribe('foo.*.baz', function(msg, reply, subject) {
  console.log('Msg received on [' + subject + '] : ' + msg);
});

nats.subscribe('foo.bar.*', function(msg, reply, subject) {
  console.log('Msg received on [' + subject + '] : ' + msg);
});

// ">" 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.subscribe('foo.>', function(msg, reply, subject) {
  console.log('Msg received on [' + subject + '] : ' + msg);
});

Queue Groups

// All subscriptions with the same queue name will form a queue group.
// Each message will be delivered to only one subscriber per queue group,
// queuing semantics. You can have as many queue groups as you wish.
// Normal subscribers will continue to work as expected.
nats.subscribe('foo', {'queue':'job.workers'}, function() {
  received += 1;
});

Clustered Usage

var nats = require('websocket-nats');

var servers = ['ws://nats.io:4222', 'ws://nats.io:5222', 'ws://nats.io:6222'];

// Randomly connect to a server in the cluster group.
var nc = nats.connect({'servers': servers});

// currentServer is the URL of the connected server.
console.log("Connected to " + nc.currentServer.host);

// Preserve order when connecting to servers.
nc = nats.connect({'dontRandomize': true, 'servers':servers});

TLS

TLS is currently not supported. You'll have to configure your websocket/TCP proxy to use TLS properly.

Secure Websockets

Connections can be made to secure websockets by using the wss protocol in the url passed to NATS.connect:

NATS.connect('wss://user:pass@localhost:4223');

Advanced Usage

// Publish with closure, callback fires when server has processed the message
nats.publish('foo', 'You done?', function() {
  console.log('msg processed!');
});

// Flush connection to server, callback fires when all messages have
// been processed.
nats.flush(function() {
  console.log('All clear!');
});

// If you want to make sure NATS yields during the processing
// of messages, you can use an option to specify a yieldTime in ms.
// During the processing of the inbound stream, we will yield if we
// spend more then yieldTime milliseconds processing.
var nc = nats.connect({port: PORT, yieldTime: 10});

// Timeouts for subscriptions
var sid = nats.subscribe('foo', function() {
  received += 1;
});

// Timeout unless a certain number of messages have been received
nats.timeout(sid, timeout_ms, expected, function() {
  timeout = true;
});

// Auto-unsubscribe after MAX_WANTED messages received
nats.subscribe('foo', {'max':MAX_WANTED});
nats.unsubscribe(sid, MAX_WANTED);

// Multiple connections
var nats = require('websocket-nats');
var nc1 = nats.connect();
var nc2 = nats.connect();

nc1.subscribe('foo');
nc2.publish('foo');

// Encodings

// By default messages received will be decoded using UTF8. To change that,
// set the encoding option on the connection.

nc = nats.connect({'servers':servers, 'encoding': 'ascii'});

See examples and benchmarks for more information..

License

(The MIT License)

Copyright (c) 2015 Apcera Inc.
Copyright (c) 2011-2015 Derek Collison

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.

websocket-nats's People

Contributors

isobit avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

websocket-nats's Issues

websocket-nats can't publish binary message(Uint8Array)

we want to publish protobuf.js encoded message,when publish the encoded Uint8Array message,the encoded frame is not correct.

nats_con=NATS.connect("ws://192.168.1.103:4223"); nats_con.publish("foo","hello string from websocket"); nats_con.subscribe("foo",function (msg) { console.log("msg:",msg) }); //the frame of the below publish is error nats_con.publish("foo",new Uint8Array(16) ); console.log("script has exec finished");

Using setImmediate

Is there some webpack magic going on here with regards to setImmediate? Given the canIuser for setImmediate, setTimeout(()=>{}, 0) seems like a better call

Binary data transfert

Hi,

I try to transfert binary buffer to a Nats client using nats-websocket-gw and websocket-nats.
But binary data don't seems to be handled well.
I get some "EOF" messages which seems to be related to a string format.

Could you tell me how to configure the connection beween websocket-nats and nats-websocket-gw in binary please?

Thanks.
Michael

websocket connect with hostname and pathname

hi,

it's glad to see it updated ๐Ÿ‘ .

And now i met a new problem - i use a proxy server before my websocket server, but url ws://127.0.0.1/websocket, always be changed as ws://127.0.0.1:null

exports.createConnection = function(url) {
	// The url is rebuilt to avoid including the auth credentials.
	var portSuffix = (url.port)? ':' + url.port : '';
	return new WebSocketProxy(url.protocol + '//' + url.hostname + portSuffix);
}

can you update it for supporting url.hostname+url.pathname, but no port.

websocket-nats halt firefox,seems a infinite loop

firefox 49.0.2 on windows 10 x64/ubuntu 16.04 x64 with ws-tcp-relay connect to gnatsd
with a simple script below,firefox has no response when load page and memory increase quickly.
test with chrome /ie 11 is ok.
`<script>

nats_con=NATS.connect("ws://192.168.1.103:4223");
//console.log("nats_con:",nats_con);
nats_con.publish("foo","hello from websocket");
nats_con.subscribe("foo",function (msg) {
    console.log("msg:",msg)
});
console.log("script has exec finished");

</script>`

Using websocket-nats in NodeJS

@isobit I have been trying to port websocket-nats to NodeJS. I have patched the net.js file to use the ws websocket library:

const WebSocket = require('ws');
let util = require('util');
let EventEmitter = require('events').EventEmitter;

function WebSocketProxy(url) {
  let self = this;
  EventEmitter.call(this);

  this.sock = new WebSocket(url, { protocolVersion: 13 });

  this.sock.on('open', function() {
    console.log('Websocket connect');
    self.emit('connect');
  });

  this.sock.on('message', function(e) {
    self.emit('data', new Buffer(e.data));
  });

  this.sock.on('error', function(e) {
    console.log('Websocket error');
    self.emit('error', e);
  });

  this.sock.on('close', function() {
    console.log('Websocket close');
    self.emit('close');
  });
}

However, when trying to connect to ws-tcp-relay I get a server (403) error:

events.js:183
      throw er; // Unhandled 'error' event
      ^
NatsError: Could not connect to server: Error: Unexpected server response: 403

If I try to connect to the [ws-tcp-relay](https://github.com/isobit/ws-tcp-relay) using other websocket clients (wscat) I get the same error.
Not sure where the issue could be - in websocket-nats or in ws-tcp-relay?
I can't connect to ws-tcp-relay with any standard NodeJS websocket library. I'm wondering if you could share some insight on what could be happening ...
Thanks.
A.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.