Giter VIP home page Giter VIP logo

nssocket's Introduction

nssocket

Version npmnpm DownloadsBuild StatusDependencies

An elegant way to define lightweight protocols on-top of TCP/TLS sockets in node.js

Motivation

Working within node.js it is very easy to write lightweight network protocols that communicate over TCP or TLS. The definition of such protocols often requires repeated (and tedious) parsing of individual TCP/TLS packets into a message header and some JSON body.

Installation

  [sudo] npm install nssocket

How it works

With nssocket this tedious bookkeeping work is done automatically for you in two ways:

  1. Leverages wildcard and namespaced events from EventEmitter2
  2. Automatically serializes messages passed to .send() and deserializes messages from data events.
  3. Implements default reconnect logic for potentially faulty connections.
  4. Automatically wraps TCP connections with TLS using a known workaround

Messages

Messages in nssocket are serialized JSON arrays of the following form:

  ["namespace", "to", "event", { "this": "is", "the": "payload" }]

Although this is not as optimal as other message formats (pure binary, msgpack) most of your applications are probably IO-bound, and not by the computation time needed for serialization / deserialization. When working with NsSocket instances, all events are namespaced under data to avoid collision with other events.

Simple Example

  var nssocket = require('nssocket');

  //
  // Create an `nssocket` TCP server
  //
  var server = nssocket.createServer(function (socket) {
    //
    // Here `socket` will be an instance of `nssocket.NsSocket`.
    //
    socket.send(['you', 'there']);
    socket.data(['iam', 'here'], function (data) {
      //
      // Good! The socket speaks our language 
      // (i.e. simple 'you::there', 'iam::here' protocol)
      //
      // { iam: true, indeedHere: true }
      //
      console.dir(data);
    })
  });
  
  //
  // Tell the server to listen on port `6785` and then connect to it
  // using another NsSocket instance.
  //
  server.listen(6785);
  
  var outbound = new nssocket.NsSocket();
  outbound.data(['you', 'there'], function () {
    outbound.send(['iam', 'here'], { iam: true, indeedHere: true });
  });
  
  outbound.connect(6785);

Reconnect Example

nssocket exposes simple options for enabling reconnection of the underlying socket. By default, these options are disabled. Lets look at a simple example:

  var net = require('net'),
      nssocket = require('nssocket');
  
  net.createServer(function (socket) {
    //
    // Close the underlying socket after `1000ms`
    //
    setTimeout(function () {
      socket.destroy();
    }, 1000);
  }).listen(8345);
  
  //
  // Create an NsSocket instance with reconnect enabled
  //
  var socket = new nssocket.NsSocket({
    reconnect: true,
    type: 'tcp4',
  });
  
  socket.on('start', function () {
    //
    // The socket will emit this event periodically
    // as it attempts to reconnect
    //
    console.dir('start');
  });
  
  socket.connect(8345);

API

socket.send(event, data)

Writes data to the socket with the specified event, on the receiving end it will look like: JSON.stringify([event, data]).

socket.on(event, callback)

Equivalent to the underlying .addListener() or .on() function on the underlying socket except that it will permit all EventEmitter2 wildcards and namespaces.

socket.data(event, callback)

Helper function for performing shorthand listeners namespaced under the data event. For example:

  //
  // These two statements are equivalent
  //
  someSocket.on(['data', 'some', 'event'], function (data) { });
  someSocket.data(['some', 'event'], function (data) { });

socket.connect(port[, host, callback])

Equivalent to the .connect() method of the underlying socket with additional error handling of the arguments passed

socket.end()

Closes the current socket, emits close event, possibly also error

socket.destroy()

Remove all listeners, destroys socket, clears buffer. It is recommended that you use socket.end().

Tests

All tests are written with vows and should be run through npm:

  $ npm test

Author: Nodejitsu

nssocket's People

Contributors

3rd-eden avatar atakangktepe avatar coderarity avatar dominictarr avatar dscape avatar genediazjr avatar indexzero avatar inindev avatar jamesonjlee avatar jcrugzz avatar kessler avatar kilianc avatar luelistan avatar mmalecki avatar nucleardreamer avatar t-k avatar vote539 avatar webglider 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nssocket's Issues

Recently added tests fail

@mmalecki Can you investigate this?

$ npm test
npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm info pretest [email protected]
npm info test [email protected]

> [email protected] test /Users/Charlie/Nodejitsu/nssocket
> vows test/*-test.js --spec


♢ nssocket/create-server


node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: ENOENT, No such file or directory
    at doConnect (net.js:549:5)
    at Socket.connect (net.js:709:5)
    at [object Object].connect (/Users/Charlie/Nodejitsu/nssocket/lib/nssocket.js:278:23)
    at Object.<anonymous> (/Users/Charlie/Nodejitsu/nssocket/test/create-server-test.js:28:26)
    at run (/Users/Charlie/Nodejitsu/nssocket/node_modules/vows/lib/vows/suite.js:132:31)
    at EventEmitter.<anonymous> (/Users/Charlie/Nodejitsu/nssocket/node_modules/vows/lib/vows/suite.js:221:40)
    at EventEmitter.<anonymous> (events.js:81:20)
    at EventEmitter.emit (/Users/Charlie/Nodejitsu/nssocket/node_modules/vows/lib/vows.js:236:24)
    at Array.<anonymous> (/Users/Charlie/Nodejitsu/nssocket/node_modules/vows/lib/vows/suite.js:162:45)
    at EventEmitter._tickCallback (node.js:126:26)

It is specifically this test which I don't expect would work because the proper unix socket type is not getting passed through: https://github.com/nodejitsu/nssocket/blob/master/test/create-server-test.js#L60

I am going to comment out the offending tests for now.

Automatic reconnect throws an exception

The clients' autoreconnect feature throws the ERRCONNREFUSED (in the underneath 'net' socket) when the server is not launched.

Scenario:
Server in NOT running, client looks like this:

var s = new nssocket.NsSocket({reconnect: true});
try {
  s.connect(5555, function (err, res) { console.log('connect cb');});
} catch (e) {
  console.log('caught ' + e); 
}

Result:

[node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: connect ECONNREFUSED
    at errnoException (net.js:646:11)
    at Object.afterConnect [as oncomplete] (net.js:637:18)]

after the client doesn't succeed to connect for the 1st time, it tries to reconnect (which is fine), but then it throws the beforementioned error.

Tested on node v0.6.12

foo & bla example seem to be broken

foo.js should connect to bla.js, etc.

However this doesn't work because foo.js throws the following exception:

/Users/dscape/Desktop/dev/nodejitsu/nssocket/node_modules/eventemitter2/lib/eventemitter2.js:283
          throw arguments[1]; // Unhandled 'error' event
                         ^
Error: NsSocket: sending on a bad socket
    at NsSocket.send (/Users/dscape/Desktop/dev/nodejitsu/nssocket/lib/nssocket.js:101:31)
    at Socket.<anonymous> (/Users/dscape/Desktop/dev/nodejitsu/nssocket/examples/foo.js:10:14)
    at Socket.EventEmitter.emit (events.js:123:20)
    at Object.afterConnect [as oncomplete] (net.js:751:10)

This is because the socket is not considered to be connected: While it is a writable socket it is not readable as no server is created in the foo.js example.

Changing:

this.connected = this.socket.writable && this.socket.readable || false;

for

this.connected = this.socket.writable || this.socket.readable || false;

Would solve the issue, but I'm unaware of other consequences this could have. Thoughts?

"close" event fired twice when end() is called

If I close my socket via

nssocket.end()

then the "close" event is fired twice. Here are the stack traces.

First event:

<<my callback function>>
at EventEmitter.emit (/path/to/project/node_modules/nssocket/node_modules/eventemitter2/lib/eventemitter2.js:339:22)
at end (/path/to/project/node_modules/nssocket/lib/nssocket.js:241:15)
at <<my function that calls end>>

Second event:

<<my callback function>>
at EventEmitter.emit (/path/to/project/node_modules/nssocket/node_modules/eventemitter2/lib/eventemitter2.js:339:22)
at _onClose (/path/to/project/node_modules/nssocket/lib/nssocket.js:457:10)
at Socket.EventEmitter.emit (events.js:95:17)
at TCP.close (net.js:465:12)

Is this being maintained?

Is anyone maintaining this repo? There are multiple issues, many of which have been fixed with pending pull requests.

TLS working only one-way

Hi,

I just checked out this library and tried to use it with TLS connections.
When a client connects to a TLS server, it receives messages by the server. But the server does not receive messages sent by the client.

The reason is that nssocket.js's _setup method only works for TLS client sockets, not for sockets returned by the server (accept), because the receiving "data" event is bound in this event handler:

this.socket.once('connect', function () {
   ...

...and a onconnect event is only raised in a client socket, not for the socket returned by the server, as this is already connected.

I changed the _setup method to the following and it seems to work for me:


//
// ### @private function _setup ()
// Sets up the underlying socket associate with this instance.
//
NsSocket.prototype._setup = function () {
  var self = this,
      startName;

  function bindData(sock) {
    Lazy(sock)
      .lines
      .map(String)
      .forEach(self._onData.bind(self));
  }

  //
  // Because of how the code node.js `tls` module works, we have 
  // to separate some bindings. The main difference is on 
  // connection, some socket activities.
  //
  if (this._type === 'tcp4') {
    startName = 'connect';

    bindData(this.socket);

    // create a stub for the setKeepAlive functionality
    this.setKeepAlive = function () {
      self.socket.setKeepAlive.apply(self.socket, arguments);
    };
  }
  else if (this._type === 'tls') {
    startName = 'secureConnection';

    if (this.connected) {
      bindData(self.socket);  
    } else {
      this.socket.once('connect', function () {
        console.log("on connect event");
        bindData(self.socket.cleartext);      
      }); 
    }

    // create a stub for the setKeepAlive functionality
    this.setKeepAlive = function () {
      self.socket.socket.setKeepAlive.apply(self.socket.socket, arguments);
    };
  }
  else {
    // bad arguments, so throw an error
    this.emit('error', new Error('Bad Option Argument [type]'));
    return null;
  }

  // make sure we listen to the underlying socket
  this.socket.on(startName, this._onStart.bind(this));
  this.socket.on('close',   this._onClose.bind(this));

  if (this.socket.socket) {
    //
    // otherwise we get a error passed from net.js
    // they need to backport the fix from v5 to v4
    //
    this.socket.socket.on('error', this._onError.bind(this));
  }

  this.socket.on('error',   this._onError.bind(this));
  this.socket.on('timeout', this._onIdle.bind(this));
};

(I might do a pull request later)

socket.send() outside createServer

I am semi-new to Node.JS and IO based writing.
Is there a way I access the socket var that is passed into the anonymous function of createServer I when creating the nssocket outside of the anonymous function?

var server = nssocket.createServer(function (socket) {
    socket.send('ello',{ testing:'test'});
    socket.data('iam', function (data) {
        console.dir(data);
    })
}).listen(6785);

example:

server.sockets[SOCKET_ID].send('event',{"msg":data});

Or a way to broadcast if there are multiple connections.

thanks

Retry backoff rate is a tad ridiculous, or I'm misreading something....

From what I've seen in the code and behaviour after user (correct me if I'm wrong), currently the exponential reconnect backoff rate is a bit overboard.

The current formula is for reconnect wait is configured_wait * 10^retry_attemps
With defaults:

  • configured_wait: 5000
  • max_retry_attemps: 10

You get an a reconnect pattern as such:

  1. 5,000 (5 Seconds)
  2. 50,000 (50 seconds)
  3. 500,000 (~8 minutes)
  4. 5,000,000 (~1 hour)
  5. 50,000,000 (~13 hours)
  6. 500,000,000 (~5 days)
  7. 5,000,000,000 (~57 days)
  8. 50,000,000,000 (~1.5 years)
  9. 500,000,000,000 (~15.8 years)
  10. 5,000,000,000,000 (~158 years)

As you can see the numbers get pretty high even if only after the 3rd attempt. This potentially locks your process up with no hope of reconnecting in a viable timeframe. IMHO this completely defeats the purpose of the reconnect function.

My suggestion would be to set-up an exponential back-off rate which plateaus towards a maximum wait time. Graph would something like this: https://en.wikipedia.org/wiki/Sigmoid_function

License?

I don't see a license associated with this project. Is there one? If so, what type?

Cannot install on node 4.2.3+

Getting this in the install log:


➜  nssocket git:(master) npm i 
\
> [email protected] install /Users/vladikoff/dev/nssocket/node_modules/msgpack
> node-gyp rebuild

  CXX(target) Release/obj.target/libmsgpack/deps/msgpack/gcc_atomic.o
  CXX(target) Release/obj.target/libmsgpack/deps/msgpack/object.o
  CC(target) Release/obj.target/libmsgpack/deps/msgpack/objectc.o
  CC(target) Release/obj.target/libmsgpack/deps/msgpack/unpack.o
../deps/msgpack/unpack.c:59:43: warning: missing field 'via' initializer [-Wmissing-field-initializers]
{ msgpack_object o = { MSGPACK_OBJECT_NIL }; return o; }
                                          ^
1 warning generated.
  CC(target) Release/obj.target/libmsgpack/deps/msgpack/vrefbuffer.o
  CC(target) Release/obj.target/libmsgpack/deps/msgpack/zone.o
  CC(target) Release/obj.target/libmsgpack/deps/msgpack/version.o
  LIBTOOL-STATIC Release/msgpack.a
  CXX(target) Release/obj.target/msgpackBinding/src/msgpack.o
In file included from ../src/msgpack.cc:9:
../node_modules/nan/nan.h:324:27: error: redefinition of 'NanEnsureHandleOrPersistent'
  NAN_INLINE v8::Local<T> NanEnsureHandleOrPersistent(const v8::Local<T> &val) {
                          ^
../node_modules/nan/nan.h:319:17: note: previous definition is here
  v8::Handle<T> NanEnsureHandleOrPersistent(const v8::Handle<T> &val) {
                ^
../node_modules/nan/nan.h:344:27: error: redefinition of 'NanEnsureLocal'
  NAN_INLINE v8::Local<T> NanEnsureLocal(const v8::Handle<T> &val) {
                          ^
../node_modules/nan/nan.h:334:27: note: previous definition is here
  NAN_INLINE v8::Local<T> NanEnsureLocal(const v8::Local<T> &val) {
                          ^
../node_modules/nan/nan.h:757:13: error: no member named 'smalloc' in namespace 'node'
    , node::smalloc::FreeCallback callback
      ~~~~~~^
../node_modules/nan/nan.h:768:12: error: no matching function for call to 'New'
    return node::Buffer::New(v8::Isolate::GetCurrent(), data, size);
           ^~~~~~~~~~~~~~~~~
/Users/vladikoff/.node-gyp/4.2.3/include/node/node_buffer.h:31:40: note: candidate function not viable: no known conversion from 'uint32_t'
      (aka 'unsigned int') to 'enum encoding' for 3rd argument
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node_buffer.h:43:40: note: candidate function not viable: 2nd argument ('const char *') would lose const
      qualifier
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node_buffer.h:28:40: note: candidate function not viable: requires 2 arguments, but 3 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate, size_t length);
                                       ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node_buffer.h:36:40: note: candidate function not viable: requires 5 arguments, but 3 were provided
NODE_EXTERN v8::MaybeLocal<v8::Object> New(v8::Isolate* isolate,
                                       ^
In file included from ../src/msgpack.cc:9:
../node_modules/nan/nan.h:772:12: error: no viable conversion from 'v8::MaybeLocal<v8::Object>' to 'v8::Local<v8::Object>'
    return node::Buffer::New(v8::Isolate::GetCurrent(), size);
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:210:7: note: candidate constructor (the implicit copy constructor) not viable: no known conversion from
      'v8::MaybeLocal<v8::Object>' to 'const v8::Local<v8::Object> &' for 1st argument
class Local {
      ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:210:7: note: candidate constructor (the implicit move constructor) not viable: no known conversion from
      'v8::MaybeLocal<v8::Object>' to 'v8::Local<v8::Object> &&' for 1st argument
class Local {
      ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:214:13: note: candidate template ignored: could not match 'Local' against 'MaybeLocal'
  V8_INLINE Local(Local<S> that)
            ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:326:13: note: candidate template ignored: could not match 'S *' against 'v8::MaybeLocal<v8::Object>'
  V8_INLINE Local(S* that)
            ^
In file included from ../src/msgpack.cc:9:
../node_modules/nan/nan.h:779:26: error: no member named 'Use' in namespace 'node::Buffer'
    return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size);
           ~~~~~~~~~~~~~~^
../src/msgpack.cc:155:50: warning: 'DecodeBytes' is deprecated: Use DecodeBytes(isolate, ...) [-Wdeprecated-declarations]
        mo->via.raw.size = static_cast<uint32_t>(DecodeBytes(v8obj, UTF8));
                                                 ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:318:32: note: 'DecodeBytes' has been explicitly marked deprecated here
                inline ssize_t DecodeBytes(
                               ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:66:42: note: expanded from macro 'NODE_DEPRECATED'
    __attribute__((deprecated(message))) declarator
                                         ^
../src/msgpack.cc:158:9: warning: 'DecodeWrite' is deprecated: Use DecodeWrite(isolate, ...) [-Wdeprecated-declarations]
        DecodeWrite((char*) mo->via.raw.ptr, mo->via.raw.size, v8obj, UTF8);
        ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:331:32: note: 'DecodeWrite' has been explicitly marked deprecated here
                inline ssize_t DecodeWrite(char* buf,
                               ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:66:42: note: expanded from macro 'NODE_DEPRECATED'
    __attribute__((deprecated(message))) declarator
                                         ^
../src/msgpack.cc:165:50: warning: 'DecodeBytes' is deprecated: Use DecodeBytes(isolate, ...) [-Wdeprecated-declarations]
        mo->via.raw.size = static_cast<uint32_t>(DecodeBytes(result, UTF8));
                                                 ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:318:32: note: 'DecodeBytes' has been explicitly marked deprecated here
                inline ssize_t DecodeBytes(
                               ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:66:42: note: expanded from macro 'NODE_DEPRECATED'
    __attribute__((deprecated(message))) declarator
                                         ^
../src/msgpack.cc:168:9: warning: 'DecodeWrite' is deprecated: Use DecodeWrite(isolate, ...) [-Wdeprecated-declarations]
        DecodeWrite((char*) mo->via.raw.ptr, mo->via.raw.size, result, UTF8);
        ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:331:32: note: 'DecodeWrite' has been explicitly marked deprecated here
                inline ssize_t DecodeWrite(char* buf,
                               ^
/Users/vladikoff/.node-gyp/4.2.3/include/node/node.h:66:42: note: expanded from macro 'NODE_DEPRECATED'
    __attribute__((deprecated(message))) declarator
                                         ^
../src/msgpack.cc:316:32: error: no matching function for call to 'NanNewBufferHandle'
    Local<Object> slowBuffer = NanNewBufferHandle(
                               ^~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:754:36: note: candidate function not viable: no known conversion from 'void (char *, void *)' to 'int' for 3rd argument
  NAN_INLINE v8::Local<v8::Object> NanNewBufferHandle (
                                   ^
../node_modules/nan/nan.h:764:36: note: candidate function not viable: requires 2 arguments, but 4 were provided
  NAN_INLINE v8::Local<v8::Object> NanNewBufferHandle (
                                   ^
../node_modules/nan/nan.h:771:36: note: candidate function not viable: requires single argument 'size', but 4 arguments were provided
  NAN_INLINE v8::Local<v8::Object> NanNewBufferHandle (uint32_t size) {
                                   ^
In file included from ../src/msgpack.cc:1:
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:221:5: error: assigning to 'v8::Primitive *volatile' from incompatible type 'v8::Value *'
    TYPE_CHECK(T, S);
    ^~~~~~~~~~~~~~~~
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:180:37: note: expanded from macro 'TYPE_CHECK'
    *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
                                    ^ ~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:501:12: note: in instantiation of function template specialization 'v8::Local<v8::Primitive>::Local<v8::Value>' requested here
    return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent())));
           ^
../node_modules/nan/nan.h:483:30: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(Nan::imp::NanEnsureLocal(val))
                             ^
In file included from ../src/msgpack.cc:1:
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:221:5: error: assigning to 'v8::Boolean *volatile' from incompatible type 'v8::Value *'
    TYPE_CHECK(T, S);
    ^~~~~~~~~~~~~~~~
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:180:37: note: expanded from macro 'TYPE_CHECK'
    *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
                                    ^ ~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:511:12: note: in instantiation of function template specialization 'v8::Local<v8::Boolean>::Local<v8::Value>' requested here
    return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent())));
           ^
../node_modules/nan/nan.h:483:30: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(Nan::imp::NanEnsureLocal(val))
                             ^
In file included from ../src/msgpack.cc:1:
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:221:5: error: assigning to 'v8::Function *volatile' from incompatible type 'v8::Value *'
    TYPE_CHECK(T, S);
    ^~~~~~~~~~~~~~~~
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:180:37: note: expanded from macro 'TYPE_CHECK'
    *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
                                    ^ ~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:1645:12: note: in instantiation of function template specialization 'v8::Local<v8::Function>::Local<v8::Value>' requested here
    return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex)
           ^
../node_modules/nan/nan.h:483:30: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(Nan::imp::NanEnsureLocal(val))
                             ^
In file included from ../src/msgpack.cc:1:
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:221:5: error: assigning to 'v8::Object *volatile' from incompatible type 'v8::Value *'
    TYPE_CHECK(T, S);
    ^~~~~~~~~~~~~~~~
/Users/vladikoff/.node-gyp/4.2.3/include/node/v8.h:180:37: note: expanded from macro 'TYPE_CHECK'
    *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);      \
                                    ^ ~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:1776:12: note: in instantiation of function template specialization 'v8::Local<v8::Object>::Local<v8::Value>' requested here
    return NanEscapeScope(
           ^
../node_modules/nan/nan.h:483:30: note: expanded from macro 'NanEscapeScope'
# define NanEscapeScope(val) scope.Escape(Nan::imp::NanEnsureLocal(val))
                             ^
4 warnings and 11 errors generated.
make: *** [Release/obj.target/msgpackBinding/src/msgpack.o] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 15.2.0
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/vladikoff/dev/nssocket/node_modules/msgpack
gyp ERR! node -v v4.2.3
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok 
npm ERR! Darwin 15.2.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "i"
npm ERR! node v4.2.3
npm ERR! npm  v2.14.7
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the msgpack package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls msgpack
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/vladikoff/dev/nssocket/npm-debug.log
➜  nssocket git:(master) node --version
v4.2.3
➜  nssocket git:(master) npm --version
2.14.7

Reconnect loosing server IP

I'm trying to use the reconnect feature between my server and client, which are both located on different machines from each other. The first connect works fine then when I kill the server and have the client try to reconnect, the IP address gets set to 127.0.0.1 instead of the IP used before. The port I used at first is still used with the reconnect.

It looks like the previously used IP is not getting passed through to the new socket when the reconnect happens. Any ideas?

Deprecation Warning

Node prompts warning for Buffer. We should replace Buffer by new Buffer for errorless package.

connect from another language

I'm trying to connect to a socket server created in nodejs from a client created in c++, the connection is done successfully, but how can I send data to a specific event.

Completely revert to 0.3.8

I don't know how #12 got merged in; it breaks everything. I'm going to publish a hot-fix to v0.3.9 now, but v0.4.0 will revert all of the changes between v0.3.8 and 4778e93

Reconnect is broken

See here.

// Attempts to reconnect the current socket on `close` or `error`.

Yes, This is true. It tries to reconnect 2 times: 1 reconnect call from _onError and second from _onClose. NsSocket.prototype.reconnect is not guarded for multiple reconnects.

NSSocket server loses requests when responses are sent by child process.

Server code:
var worker = child_process.fork('child.js');
var server = nssocket.createServer(function(socket) {
socket.data('data', function (data) {
worker.send(data.toString('utf8'), socket.socket, {keepOpen: true});
});
});

child.js
process.on('message', function(data, socket) {
send(socket, 'data', data);
});

function send(socket, event, data, callback) {
var delimiter = '::';
if (typeof event === 'string') {
event = event.split(delimiter);
}
var message = Buffer(JSON.stringify(event.concat(data)) + '\n');

socket.write(message, callback);
};

The client send 10 requests and after timeout from 1000 milliseconds send another 10 request and so on.
The first 10 request have their responses, but next lost responses.

I use nssocker v0.6.0, Node.js v6.9.4 and testing on Windows 10 with NetBeans IDE 8.2

Can anyone take the task of maintaining this library?

I can see that this library is being download over 700K times weekly. So this is a much popular library. But it is not maintained. Can anyone please take the task of maintaining it.

Many of the tls socket functionalities are deprecated and are reducing the usability of this library.

Exceptions get swallowed in event handlers

var nssocket = require('../lib/nssocket');

//
// define a simple message protocol as [<type>, <id>] and create some messages that use it.
//
var message1 = ['message', 'one'];
var message2 = ['message', 'two'];

//
// Create an `nssocket` TCP server and tell the server to listen on port `6785`.
//
var server = nssocket.createServer(function (socket) {

  //
  // Here `socket` will be an instance of `nssocket.NsSocket`.
  // When there is a connection, send `message1` to the socket.
  //
  socket.send(message1);

  //
  // listen for `message2` from the connecting socket.
  //
  socket.data(message2, function (data) {
    console.log('executed');
    lol(); // should crash the server
    console.log('wat');

    //
    // If this callback is called, we know that the socket
    // speaks our language, we will likely be provided with
    // a payload. In this case `{ "foo": "bar" }`.
    //
    console.dir(data);
    process.exit();
  })

}).listen(6785);

//
// Create a new `nssocket` instance and then connect to the server in 1000 miliseconds.
//
setTimeout(function() {

  var outbound = new nssocket.NsSocket();

  outbound.data(message1, function () {
    outbound.send(message2, { "foo": "bar" });
  });

  outbound.connect(6785);

}, 1000);

Is this project stale?

I haven't seen much activity and there are a few PRs out there. What's the status? I would be more than willing to help maintain.

nssocket docs/usage is confusing for sending/receiving.

cc @dominictarr

Documentation is confusing, so rework as such

  1. if you send, maybe have recv (binds to 'on')
  2. send(namespaceArray, data)
  3. recv(namespaceArray || namespace, function (namespaceArray, data) {})
  4. cleanup docs.

this should be rolled into 2.x, and worked in for 3.0 release.

NsSocket.connect assumes port

Although NsSocket.listen allows you to listen on a Unix Socket, there is no connect function for it.
Should connect not be a passthrough function for all the net.Socket.connect types?

Accessing event name in callback

['event1', 'event2']
.forEach(function (event) {
  socket.data(event, data.bind(self, event));
})

But what about generic event names? It is not possible to predict event. We've found a way in examples:

outbound.data(['drink', '*'], function () {
  console.log('I can mix a', this.event[2], 'drink');
});

There is no information about this.event in docs. This is very important, please fix.

Closing client socket with auto reconnect enabled

When closing client socket with 'reconnect' enabled using socket.end() scheduled reconnect function will crash the application (~line 322 in nssocket.js, when removing listeners from socket).
If I try socket.destroy() reconnect function would recreate the internal socket and connect to server, but it shouldn't, application requested closing of socket.

cannot listen to destroy events?

Maybe I'm missing something here, but it seems by the implementation of this method that one cannot listen on destroy event, since once destroy is called all listeners are removed:

NsSocket.prototype.destroy = function destroy() {
  // this should be forcibly remove EVERY listener
  this.removeAllListeners();    // <---------------------

  if (this.socket) {
    try {
      this.socket.end(); // send FIN
      this.socket.destroy(); // make sure fd's are gone
    }
    catch (ex) {
      // do nothing on errors
    }
  }

  // clear buffer
  this.data = '';
  this.emit('destroy');    // <---------------------
};

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.