How to use maybeReconnect method in redwood

Best JavaScript code snippet using redwood

socket.js

Source:socket.js Github

copy

Full Screen

1/**2 * socket.io3 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>4 * MIT Licensed5 */6(function (exports, io, global) {7 /**8 * Expose constructor.9 */10 exports.Socket = Socket;11 /**12 * Create a new `Socket.IO client` which can establish a persistent13 * connection with a Socket.IO enabled server.14 *15 * @api public16 */17 function Socket (options) {18 this.options = {19 port: 8020 , secure: false21 , document: 'document' in global ? document : false22 , resource: 'socket.io'23 , transports: io.transports24 , 'connect timeout': 1000025 , 'try multiple transports': true26 , 'reconnect': true27 , 'reconnection delay': 50028 , 'reconnection limit': Infinity29 , 'reopen delay': 300030 , 'max reconnection attempts': 1031 , 'sync disconnect on unload': false32 , 'auto connect': true33 , 'flash policy port': 1084334 , 'manualFlush': false35 };36 io.util.merge(this.options, options);37 this.connected = false;38 this.open = false;39 this.connecting = false;40 this.reconnecting = false;41 this.namespaces = {};42 this.buffer = [];43 this.doBuffer = false;44 if (this.options['sync disconnect on unload'] &&45 (!this.isXDomain() || io.util.ua.hasCORS)) {46 var self = this;47 io.util.on(global, 'beforeunload', function () {48 self.disconnectSync();49 }, false);50 }51 if (this.options['auto connect']) {52 this.connect();53 }54};55 /**56 * Apply EventEmitter mixin.57 */58 io.util.mixin(Socket, io.EventEmitter);59 /**60 * Returns a namespace listener/emitter for this socket61 *62 * @api public63 */64 Socket.prototype.of = function (name) {65 if (!this.namespaces[name]) {66 this.namespaces[name] = new io.SocketNamespace(this, name);67 if (name !== '') {68 this.namespaces[name].packet({ type: 'connect' });69 }70 }71 return this.namespaces[name];72 };73 /**74 * Emits the given event to the Socket and all namespaces75 *76 * @api private77 */78 Socket.prototype.publish = function () {79 this.emit.apply(this, arguments);80 var nsp;81 for (var i in this.namespaces) {82 if (this.namespaces.hasOwnProperty(i)) {83 nsp = this.of(i);84 nsp.$emit.apply(nsp, arguments);85 }86 }87 };88 /**89 * Performs the handshake90 *91 * @api private92 */93 function empty () { };94 Socket.prototype.handshake = function (fn) {95 var self = this96 , options = this.options;97 function complete (data) {98 if (data instanceof Error) {99 self.connecting = false;100 self.onError(data.message);101 } else {102 fn.apply(null, data.split(':'));103 }104 };105 var url = [106 'http' + (options.secure ? 's' : '') + ':/'107 , options.host + ':' + options.port108 , options.resource109 , io.protocol110 , io.util.query(this.options.query, 't=' + +new Date)111 ].join('/');112 if (this.isXDomain() && !io.util.ua.hasCORS) {113 var insertAt = document.getElementsByTagName('script')[0]114 , script = document.createElement('script');115 script.src = url + '&jsonp=' + io.j.length;116 insertAt.parentNode.insertBefore(script, insertAt);117 io.j.push(function (data) {118 complete(data);119 script.parentNode.removeChild(script);120 });121 } else {122 var xhr = io.util.request();123 xhr.open('GET', url, true);124 if (this.isXDomain()) {125 xhr.withCredentials = true;126 }127 xhr.onreadystatechange = function () {128 if (xhr.readyState == 4) {129 xhr.onreadystatechange = empty;130 if (xhr.status == 200) {131 complete(xhr.responseText);132 } else if (xhr.status == 403) {133 self.onError(xhr.responseText);134 } else {135 self.connecting = false; 136 !self.reconnecting && self.onError(xhr.responseText);137 }138 }139 };140 xhr.send(null);141 }142 };143 /**144 * Find an available transport based on the options supplied in the constructor.145 *146 * @api private147 */148 Socket.prototype.getTransport = function (override) {149 var transports = override || this.transports, match;150 for (var i = 0, transport; transport = transports[i]; i++) {151 if (io.Transport[transport]152 && io.Transport[transport].check(this)153 && (!this.isXDomain() || io.Transport[transport].xdomainCheck(this))) {154 return new io.Transport[transport](this, this.sessionid);155 }156 }157 return null;158 };159 /**160 * Connects to the server.161 *162 * @param {Function} [fn] Callback.163 * @returns {io.Socket}164 * @api public165 */166 Socket.prototype.connect = function (fn) {167 if (this.connecting) {168 return this;169 }170 var self = this;171 self.connecting = true;172 173 this.handshake(function (sid, heartbeat, close, transports) {174 self.sessionid = sid;175 self.closeTimeout = close * 1000;176 self.heartbeatTimeout = heartbeat * 1000;177 if(!self.transports)178 self.transports = self.origTransports = (transports ? io.util.intersect(179 transports.split(',')180 , self.options.transports181 ) : self.options.transports);182 self.setHeartbeatTimeout();183 function connect (transports){184 if (self.transport) self.transport.clearTimeouts();185 self.transport = self.getTransport(transports);186 if (!self.transport) return self.publish('connect_failed');187 // once the transport is ready188 self.transport.ready(self, function () {189 self.connecting = true;190 self.publish('connecting', self.transport.name);191 self.transport.open();192 if (self.options['connect timeout']) {193 self.connectTimeoutTimer = setTimeout(function () {194 if (!self.connected) {195 self.connecting = false;196 if (self.options['try multiple transports']) {197 var remaining = self.transports;198 while (remaining.length > 0 && remaining.splice(0,1)[0] !=199 self.transport.name) {}200 if (remaining.length){201 connect(remaining);202 } else {203 self.publish('connect_failed');204 }205 }206 }207 }, self.options['connect timeout']);208 }209 });210 }211 connect(self.transports);212 self.once('connect', function (){213 clearTimeout(self.connectTimeoutTimer);214 fn && typeof fn == 'function' && fn();215 });216 });217 return this;218 };219 /**220 * Clears and sets a new heartbeat timeout using the value given by the221 * server during the handshake.222 *223 * @api private224 */225 Socket.prototype.setHeartbeatTimeout = function () {226 clearTimeout(this.heartbeatTimeoutTimer);227 if(this.transport && !this.transport.heartbeats()) return;228 var self = this;229 this.heartbeatTimeoutTimer = setTimeout(function () {230 self.transport.onClose();231 }, this.heartbeatTimeout);232 };233 /**234 * Sends a message.235 *236 * @param {Object} data packet.237 * @returns {io.Socket}238 * @api public239 */240 Socket.prototype.packet = function (data) {241 if (this.connected && !this.doBuffer) {242 this.transport.packet(data);243 } else {244 this.buffer.push(data);245 }246 return this;247 };248 /**249 * Sets buffer state250 *251 * @api private252 */253 Socket.prototype.setBuffer = function (v) {254 this.doBuffer = v;255 if (!v && this.connected && this.buffer.length) {256 if (!this.options['manualFlush']) {257 this.flushBuffer();258 }259 }260 };261 /**262 * Flushes the buffer data over the wire.263 * To be invoked manually when 'manualFlush' is set to true.264 *265 * @api public266 */267 Socket.prototype.flushBuffer = function() {268 this.transport.payload(this.buffer);269 this.buffer = [];270 };271 272 /**273 * Disconnect the established connect.274 *275 * @returns {io.Socket}276 * @api public277 */278 Socket.prototype.disconnect = function () {279 if (this.connected || this.connecting) {280 if (this.open) {281 this.of('').packet({ type: 'disconnect' });282 }283 // handle disconnection immediately284 this.onDisconnect('booted');285 }286 return this;287 };288 /**289 * Disconnects the socket with a sync XHR.290 *291 * @api private292 */293 Socket.prototype.disconnectSync = function () {294 // ensure disconnection295 var xhr = io.util.request();296 var uri = [297 'http' + (this.options.secure ? 's' : '') + ':/'298 , this.options.host + ':' + this.options.port299 , this.options.resource300 , io.protocol301 , ''302 , this.sessionid303 ].join('/') + '/?disconnect=1';304 xhr.open('GET', uri, false);305 xhr.send(null);306 // handle disconnection immediately307 this.onDisconnect('booted');308 };309 /**310 * Check if we need to use cross domain enabled transports. Cross domain would311 * be a different port or different domain name.312 *313 * @returns {Boolean}314 * @api private315 */316 Socket.prototype.isXDomain = function () {317 // if node318 return false;319 // end node320 var port = global.location.port ||321 ('https:' == global.location.protocol ? 443 : 80);322 return this.options.host !== global.location.hostname 323 || this.options.port != port;324 };325 /**326 * Called upon handshake.327 *328 * @api private329 */330 Socket.prototype.onConnect = function () {331 if (!this.connected) {332 this.connected = true;333 this.connecting = false;334 if (!this.doBuffer) {335 // make sure to flush the buffer336 this.setBuffer(false);337 }338 this.emit('connect');339 }340 };341 /**342 * Called when the transport opens343 *344 * @api private345 */346 Socket.prototype.onOpen = function () {347 this.open = true;348 };349 /**350 * Called when the transport closes.351 *352 * @api private353 */354 Socket.prototype.onClose = function () {355 this.open = false;356 clearTimeout(this.heartbeatTimeoutTimer);357 };358 /**359 * Called when the transport first opens a connection360 *361 * @param text362 */363 Socket.prototype.onPacket = function (packet) {364 this.of(packet.endpoint).onPacket(packet);365 };366 /**367 * Handles an error.368 *369 * @api private370 */371 Socket.prototype.onError = function (err) {372 if (err && err.advice) {373 if (err.advice === 'reconnect' && (this.connected || this.connecting)) {374 this.disconnect();375 if (this.options.reconnect) {376 this.reconnect();377 }378 }379 }380 this.publish('error', err && err.reason ? err.reason : err);381 };382 /**383 * Called when the transport disconnects.384 *385 * @api private386 */387 Socket.prototype.onDisconnect = function (reason) {388 var wasConnected = this.connected389 , wasConnecting = this.connecting;390 this.connected = false;391 this.connecting = false;392 this.open = false;393 if (wasConnected || wasConnecting) {394 this.transport.close();395 this.transport.clearTimeouts();396 if (wasConnected) {397 this.publish('disconnect', reason);398 if ('booted' != reason && this.options.reconnect && !this.reconnecting) {399 this.reconnect();400 }401 }402 }403 };404 /**405 * Called upon reconnection.406 *407 * @api private408 */409 Socket.prototype.reconnect = function () {410 this.reconnecting = true;411 this.reconnectionAttempts = 0;412 this.reconnectionDelay = this.options['reconnection delay'];413 var self = this414 , maxAttempts = this.options['max reconnection attempts']415 , tryMultiple = this.options['try multiple transports']416 , limit = this.options['reconnection limit'];417 function reset () {418 if (self.connected) {419 for (var i in self.namespaces) {420 if (self.namespaces.hasOwnProperty(i) && '' !== i) {421 self.namespaces[i].packet({ type: 'connect' });422 }423 }424 self.publish('reconnect', self.transport.name, self.reconnectionAttempts);425 }426 clearTimeout(self.reconnectionTimer);427 self.removeListener('connect_failed', maybeReconnect);428 self.removeListener('connect', maybeReconnect);429 self.reconnecting = false;430 delete self.reconnectionAttempts;431 delete self.reconnectionDelay;432 delete self.reconnectionTimer;433 delete self.redoTransports;434 self.options['try multiple transports'] = tryMultiple;435 };436 function maybeReconnect () {437 if (!self.reconnecting) {438 return;439 }440 if (self.connected) {441 return reset();442 };443 if (self.connecting && self.reconnecting) {444 return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);445 }446 if (self.reconnectionAttempts++ >= maxAttempts) {447 if (!self.redoTransports) {448 self.on('connect_failed', maybeReconnect);449 self.options['try multiple transports'] = true;450 self.transports = self.origTransports;451 self.transport = self.getTransport();452 self.redoTransports = true;453 self.connect();454 } else {455 self.publish('reconnect_failed');456 reset();457 }458 } else {459 if (self.reconnectionDelay < limit) {460 self.reconnectionDelay *= 2; // exponential back off461 }462 self.connect();463 self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);464 self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);465 }466 };467 this.options['try multiple transports'] = false;468 this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);469 this.on('connect', maybeReconnect);470 };471})(472 'undefined' != typeof io ? io : module.exports473 , 'undefined' != typeof io ? io : module.parent.exports474 , this...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood-client');2var client = redwood.createClient();3client.maybeReconnect();4var redwood = require('redwood-client');5var client = redwood.createClient();6client.maybeReconnect();7var redwood = require('redwood-client');8var client = redwood.createClient();9client.maybeReconnect();10var redwood = require('redwood-client');11var client = redwood.createClient();12client.maybeReconnect();13var redwood = require('redwood-client');14var client = redwood.createClient();15client.maybeReconnect();16var redwood = require('redwood-client');17var client = redwood.createClient();18client.maybeReconnect();19var redwood = require('redwood-client');20var client = redwood.createClient();21client.maybeReconnect();22var redwood = require('redwood-client');23var client = redwood.createClient();24client.maybeReconnect();25var redwood = require('redwood-client');26var client = redwood.createClient();27client.maybeReconnect();28var redwood = require('redwood-client');29var client = redwood.createClient();30client.maybeReconnect();31var redwood = require('redwood-client');32var client = redwood.createClient();33client.maybeReconnect();34var redwood = require('redwood-client');35var client = redwood.createClient();36client.maybeReconnect();

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwoodClient = require('./redwoodClient');2redwoodClient.maybeReconnect();3var redwoodClient = {4 maybeReconnect: function(){5 }6};7module.exports = redwoodClient;8var redwoodClient = require('./redwoodClient');9redwoodClient.maybeReconnect();10var redwoodClient = {11 maybeReconnect: function(){12 }13};14module.exports = redwoodClient;15var redwoodClient = require('./redwoodClient');16redwoodClient.maybeReconnect();17var redwoodClient = {18 maybeReconnect: function(){19 }20};21module.exports = redwoodClient;

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2var redwoodClient = redwood.createClient({3});4var redwoodClient2 = redwood.createClient({5});6redwoodClient.maybeReconnect(function (err, data) {7 if (err) {8 console.log(err);9 } else {10 console.log(data);11 }12});13redwoodClient2.maybeReconnect(function (err, data) {14 if (err) {15 console.log(err);16 } else {17 console.log(data);18 }19});

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('./redwood.js');2var rw = new redwood.Redwood();3rw.maybeReconnect();4var Redwood = function() {5 this.maybeReconnect = function() {6 console.log("maybeReconnect");7 }8}9exports.Redwood = Redwood;

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2var config = {3};4var db = redwood.createClient(config);5db.on('connect', function () {6 console.log('connected');7});8db.on('reconnecting', function () {9 console.log('reconnecting');10});11db.on('ready', function () {12 console.log('ready');13});14db.on('error', function (err) {15 console.log('error', err);16});17db.maybeReconnect();18var db = redwood.createClient(config);19db.on('connect', function () {20 console.log('connected');21});22db.on('reconnecting', function () {23 console.log('reconnecting');24});25db.on('ready', function () {26 console.log('ready');27});28db.on('error', function (err) {29 console.log('error', err);30});31db.maybeReconnect();32var redwood = require('redwood');33var config = {34};35var db = redwood.createClient(config);36db.on('connect', function () {37 console.log('connected');38});39db.on('reconnecting', function () {40 console.log('reconnecting');41});42db.on('ready', function () {43 console.log('ready');44});45db.on('error', function (err) {46 console.log('error', err);47});48db.reconnect();

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwoodjs');2var db = new redwood.Db();3 if (err) throw err;4 console.log("connected!");5});6setTimeout(function() {7 console.log("killing db server");8 db.connection.close();9}, 10000);10setTimeout(function() {11 console.log("trying to reconnect");12 db.maybeReconnect(function(err) {13 if (err) throw err;14 console.log("reconnected!");15 });16}, 20000);

Full Screen

Using AI Code Generation

copy

Full Screen

1const redwood = require('redwood-client');2const client = new redwood.Client();3 if (err) {4 console.error('could not connect');5 console.error(err);6 return;7 }8 console.log('connected');9 client.maybeReconnect();10});11 client.maybeReconnect();12 at Object.<anonymous> (C:\Users\myusername\Documents\redwood-client\test.js:13:9)13 at Module._compile (module.js:652:30)14 at Object.Module._extensions..js (module.js:663:10)15 at Module.load (module.js:565:32)16 at tryModuleLoad (module.js:505:12)17 at Function.Module._load (module.js:497:3)18 at Function.Module.runMain (module.js:693:10)19 at startup (bootstrap_node.js:188:16)20const redwood = require('redwood-client');21const client = new redwood.Client();22 if (err) {23 console.error('could not connect');24 console.error(err);25 return;26 }27 console.log('connected');28 client.maybeReconnect();29});30 client.maybeReconnect();

Full Screen

Using AI Code Generation

copy

Full Screen

1var redwood = require('redwood');2var redis = require('redis');3var redisClient = redis.createClient();4redwood.setRedisClient(redisClient);5var redwoodClient = redwood.createClient();6var obj = {7};8redwoodClient.save(obj, function(err, obj) {9 if (err) {10 console.log('Error saving object: ' + err);11 } else {12 console.log('Object saved: ' + obj);13 }14});15redisClient.quit();16setTimeout(function() {17 var redisServer = require('redis-server');18 var server = redisServer(6379);19 server.open(function() {20 console.log('Redis server started');21 });22}, 5000);23setTimeout(function() {24 redwood.maybeReconnect(function(err) {25 if (err) {26 console.log('Error reconnecting to redis server: ' + err);27 } else {28 console.log('Reconnected to redis server');29 }30 });31}, 10000);32setTimeout(function() {33 server.close(function() {34 console.log('Redis server stopped');35 });36}, 15000);37setTimeout(function() {38 redwood.maybeReconnect(function(err) {39 if (err) {40 console.log('Error reconnecting to redis server: ' + err);41 } else {42 console.log('Reconnected to redis server');43 }44 });45}, 20000);46setTimeout(function() {47 server.open(function() {48 console.log('Redis server started');49 });50}, 25000);51setTimeout(function() {52 redwood.maybeReconnect(function(err) {53 if (err) {54 console.log('Error reconnecting to redis server: ' + err);55 } else {56 console.log('Reconnected to redis server');57 }58 });59}, 30000);60setTimeout(function() {61 server.close(function() {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run redwood automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful