Last active
August 17, 2016 02:59
-
-
Save 21paradox/de7138ce0558d4e0220b198537657513 to your computer and use it in GitHub Desktop.
dnode with websocket and reconnect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
````js | |
var dnode = require('dnode'); | |
var PassThrough = require('stream').PassThrough; | |
var inject = require('reconnect-core'); | |
var reconnect = inject(function (_url) { | |
return websocket_stream(_url); | |
}); | |
var d = dnode({ | |
clientfn1: function(){console.log(111)} | |
}); | |
/* | |
define a cacheStream here | |
dnode will write to this cacheStream | |
*/ | |
var cacheStream = new PassThrough({ | |
objectMode: false, | |
highWaterMark: 16384, //16k | |
decodeStrings: false, | |
readableObjectMode: true, | |
writableObjectMode: true | |
}); | |
/* | |
d.pipe(cacheStream); | |
do not use pipe here, it will make stream end | |
*/ | |
d.on('data', function(data) { | |
cacheStream.push(data); | |
}); | |
// add reconnect | |
var re = reconnect({}, function (ws_stream) { | |
// reset dnode status,makesure it not end | |
d._ended = false; | |
d.writable = true; | |
d.readable = true; | |
/* | |
dnode will write to cacheStream | |
if websocket conn is lost | |
data will be cached and will send after reconnect | |
*/ | |
// cache_stream -> websocket_stream | |
cacheStream.pipe(ws_stream); | |
// websocket_stream -> dnode | |
ws_stream.pipe(d); | |
d.once('end', function () { | |
// unpipe previsous streams | |
ws_stream.unpipe(d); | |
cacheStream.unpipe(ws_stream); | |
// pause cache because websocket end | |
cacheStream.pause(); | |
// reset dnode status,makesure it not end | |
d.writable = true; | |
d.readable = true; | |
}); | |
}); | |
re.on('connect', function (con) { | |
/* | |
make remote events happen again | |
*/ | |
if (d.proto) { | |
d.once('pipe', function () { | |
d.proto.start(); | |
cacheStream.resume(); | |
}); | |
} | |
debugSock('connect'); | |
}) | |
.on('reconnect', function (n, delay) { | |
console.log('try reconnect'); | |
}) | |
.on('error', function (err) { | |
console.log(err); | |
}); | |
re.connect('http://xxx.xx.xx/websocket'); | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment