Can't connect to Socket.io Error: xhr poll error - node.js

Hi i'm using Homestead with a laravel application.
I can't get the client to receive the data on from the server...
My socket.js:
var server = require('http').Server();
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('test-channel');
redis.on('message', function (channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
/*Booting Up the Server : port 3000 */
server.listen(3000 , function(){
console.log('The Server Is Running');
});
This is listening to port 3000 which is working.
Console output:
vagrant#homestead:~/code/chatting-app$ nodemon -L socket.js
[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node socket.js`
The Server Is Running
On the client side i'm also listening to port 3000.
i use a piece of code to display the error:
function checkSocketIoConnect(url, timeout) {
return new Promise(function(resolve, reject) {
var errAlready = false;
timeout = timeout || 5000;
var socket = io(url, {reconnection: false, timeout: timeout});
// success
socket.on("connect", function() {
clearTimeout(timer);
resolve();
socket.close();
});
// set our own timeout in case the socket ends some other way than what we are listening for
var timer = setTimeout(function() {
timer = null;
error("local timeout");
}, timeout);
// common error handler
function error(data) {
if (timer) {
clearTimeout(timer);
timer = null;
}
if (!errAlready) {
errAlready = true;
reject(data);
socket.disconnect();
}
}
// errors
socket.on("connect_error", error);
socket.on("connect_timeout", error);
socket.on("error", error);
socket.on("disconnect", error);
});
}
checkSocketIoConnect("http://192.168.10.10:3000").then(function() {
console.log('succes');
}, function(reason) {
console.log(reason);
});
But this displays the following error:
Error: xhr poll error
Stacktrace:
[14]</n.prototype.onError#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:24221
[17]</</o.prototype.doPoll/<#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:29697
[9]</n.prototype.emit#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:13388
[17]</</i.prototype.onError#https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.7/socket.io.min.js:1:31004
i don't know what to do?! I tried everything i can think of.
My homestead.Yaml file:
Any help is appreciated...

IT WAS ADBLOCKER
Disabled adblocker for this page and it works now.
Stupid.........

Related

Using setInterval with socket.write

This is the code that works but it writes the data just once:
var net = require('net');
var PORT = 3000;
var client = new net.Socket();
client.connect(PORT, function(){
client.write('{printing}');
})
I am looking to write the same thing every few seconds. Wrote the below code but it doesn't seem to work:
client.connect(PORT, function(){
setInterval(function(){
client.write('{ printing }');
},10000);
})
Following is the error that I keep getting:
node:events:355
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at afterWriteDispatched (node:internal/stream_base_commons:160:15)
at writeGeneric (node:internal/stream_base_commons:151:3)
at Socket._writeGeneric (node:net:773:11)
at Socket._write (node:net:785:8)
at writeOrBuffer (node:internal/streams/writable:395:12)
at Socket.Writable.write (node:internal/streams/writable:340:10)
at Timeout._onTimeout (/app/src/index.js:135:14)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
Emitted 'error' event on Socket instance at:
at emitErrorNT (node:internal/streams/destroy:188:8)
at emitErrorCloseNT (node:internal/streams/destroy:153:3)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
errno: -32,
code: 'EPIPE',
syscall: 'write'
}
[nodemon] app crashed - waiting for file changes before starting..
This is how I fixed it:
client.connect(PORT, function(){
client.write('printing')
})
//adding drain if the buffer gets full
client.on('drain',()=>{
console.log("draining the buffer")
setTimeout(() => {
client.write('printing')
})
//reading the response recieved : ("ok")
client.on('data', (data) => {})
//in case of an error, closing the connection
client.on('error',err => {}).on('close',() => {
setTimeout(() => {
client.connect(PORT, function(){
client.write('printing')
})
},40000)
})
In this context, the EPIPE error probably means that you're trying to write to a socket that has been closed. Since the setInterval() example you show keeps going forever, that probably means that the socket you originally connected gets closed at some point, but your setInterval() is still firing and trying to write to it.
You don't show the overall context of what you're trying to accomplish here to know exactly what to suggest, but at a minimum, you need to call clearInterval() to stop the timer whenever the socket it's trying to write to gets closed, either on purpose or because of error.
Here's an example for how you could debug if this is what is happening to you:
const net = require('net');
const PORT = 3000;
const client = new net.Socket();
let timer;
function disableTimer() {
if (timer) {
clearInterval(timer);
timer = null;
}
}
client.on('error', err => {
console.log("socket error", err);
disableTimer();
}).on('close', () => {
console.log("socket closed");
disableTimer();
});
client.connect(PORT, function(){
timer = setInterval(function(){
client.write('{ printing }');
},10000);
});

(index):126 Uncaught DOMException: Failed to execute 'close' on 'WebSocket': The code must be either 1000, or between 3000 and 4999. 0 is neither

I am seeing this error
(index):126 Uncaught DOMException: Failed to execute 'close' on
'WebSocket': The code must be either 1000, or between 3000 and 4999. 0
is neither.
at WebSocket. (http://localhost:3701/:126:14)
the code I am using was:
const createConnection = () => {
const socket = new WebSocket('ws://localhost:3702');
socket.addEventListener('open', function (event) {
console.log('connection made to server:', event);
});
socket.addEventListener('close', function (event) {
console.log('connection closed:', event);
socket.close(0, 'unknown'); // THIS CAUSED ERROR
createConnection();
});
socket.addEventListener('message', function (event) {
console.log('ws client received message:', event);
location.reload();
});
};
anyone know what the error is about?
Have you considered changing
socket.close(0, 'unknown');
to
socket.close(1000, 'unknown');

When mongodb server is down how to catch the error while running mongoose query

I am using mongoose for connecting node.js with mongoDB, now i wrote below query
var trans = new transmodel({method: method, trans_id: r});
trans.save(function(err) {
if (err) {
console.error("Razor_pay_webhook Error 4 err: " + err);
res.write('statusCode: 200');
res.end();
} else {
res.write('statusCode: 400');
res.end();
}
});
I thought when my mongodb cluster will be down then i will get 'err' while executing above mongoose query, but when i ran above query while my mongo cluster was down nothing happened(No err was called). Can anyone please tell me how can i catch the error if my mongodb server is down inside my query. Also for reconnecting again with my cluster i have set below parameters but my node server is not trying to reconnect again with my mongodb server i don't know what's going wrong.
var mongoose = require('mongoose');
var config = require('./config/database.js');
var DB_URL = config.db.url;
mongoose.connection.on("connected", function(ref) {
console.log("Connected to " + " DB!");
});
mongoose.connection.on("error", function(err) {
console.error('Failed to connect to DB ' + ' on startup ', err);
if (err) {
return next(err);
}
});
mongoose.connection.on('disconnected', function(err) {
console.log('Mongoose default connection to DB :' + ' disconnected');
if (err) {
return next(err);
}
});
var gracefulExit = function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection with DB :' + ' is disconnected through app termination');
process.exit(0);
});
}
process.on('SIGINT', gracefulExit).on('SIGTERM', gracefulExit);
exports.con_close = function () {
console.log('Mongoose connection disconnected');
mongoose.connection.close();
}
var options = {
server: {
socketOptions: {
keepAlive: 1000,
connectTimeoutMS: 30000
}
},
replset: {
rs_name: 'replicaset',
auto_reconnect:true,
socketOptions: {
keepAlive: 1000, // doubt about it
connectTimeoutMS: 30000
}
},
user: 'root',
pass: 'G3saGT2Y',
auth: {
authdb: 'admin'
}
}
mongoose.connect(DB_URL, options, function(err) {
console.log('ho rha hai');
if (err) {
console.log('error connection to mongo server!');
console.log(err);
}
});
You are using mongoose, it emits events (the EventEmitter pattern) when the database is down and when the database is reconnecting and up again.
from mongoose code found here we can see that the library db connection - connection.js
has the following events that are emitted:
* #param {Mongoose} base a mongoose instance
* #inherits NodeJS EventEmitter
http://nodejs.org/api/events.html#events_class_events_eventemitter
* #event connecting: Emitted when connection.{open,openSet}() is executed on this connection.
#event connected: Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.
#event open: Emitted after we connected and onOpen is executed on all of this connections models.
#event disconnecting: Emitted when connection.close() was executed.
#event disconnected: Emitted after getting disconnected from the db.
#event close: Emitted after we disconnected and onClose executed on all of this connections models.
#event reconnected: Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.
#event error: Emitted when an error occurs on this connection.
#event fullsetup: Emitted in a replica-set scenario, when primary and at
least one seconaries specified in the connection string are connected.
#event all: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.
When the database is down you will receive two events:
1. disconnected
2. error (the error that driver encountered)
When the database is up again you will receive the reconnect event.
So you don't need to try catch the error rather you should listen to these events.
More helpful information about connection failures and reconnecting can be found here.
This article explain how to use and configure the autoReconnect and the bufferMaxEntries according to your settings.

Heroku web process timeout while running a daemon server of node.js backed with mongodb

I have running a daemon server to post the social network feeds on scheduled time.
Currently, I have issue while running daemon server which is written in node.js and express framework backed with mongodb.
Please see the following error which I got from heroku logs command.
←[36m2014-11-05T12:07:26.934753+00:00 app[web.1]:←[0m Daemon worker process is online.
←[36m2014-11-05T12:07:28.147952+00:00 app[web.1]:←[0m Starting daemon server
←[36m2014-11-05T12:07:28.230621+00:00 app[web.1]:←[0m APN agent connected.
←[36m2014-11-05T12:07:27.730718+00:00 app[web.1]:←[0m Successfully connected to MongoDB
←[36m2014-11-05T12:08:27.375215+00:00 heroku[web.1]:←[0m State changed from starting to crashed
←[36m2014-11-05T12:07:23.455341+00:00 heroku[web.1]:←[0m State changed from crashed to starting
←[36m2014-11-05T12:08:26.523383+00:00 heroku[web.1]:←[0m Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
←[36m2014-11-05T12:08:26.523870+00:00 heroku[web.1]:←[0m Stopping process with SIGKILL
←[36m2014-11-05T12:08:27.369727+00:00 heroku[web.1]:←[0m Process exited with status 137
As you can see that daemon server script run successfully but after that Heroku log showing me the boot timeout error.
var cluster = require('cluster')
if(cluster.isMaster){
cluster.fork()
cluster.on('online', function(worker){
console.log('Daemon worker process is online.')
})
cluster.on('exit', function(worker){
console.log('Daemon worker process has died. Booting another.')
cluster.fork()
})
} else {
var mongoose = require('mongoose')
var mongoDbURI
if(process.argv.indexOf('localdb') != -1){
mongoDbURI = 'mongodb://[IP]/[appname]'
} else {
//mongoDbURI = 'mongodb://[db url]'
mongoDbURI = '[db url]'
}
var mongoDbOptions = {}
if(process.env.MONGODB_URI)
mongoDbURI = process.env.MONGODB_URI
if(process.env.MONGODB_OPTIONS)
mongoDbOptions = JSON.stringify(process.env.MONGODB_OPTIONS)
var Agenda = require('agenda')
var agenda = new Agenda()
.database(mongoDbURI, 'daemonTasks')
.processEvery('1 minute')
//On termination of daemon, gracefully shut down jobs
function gracefulShutdown() {
agenda.stop(function() {
console.log("Shutting down daemon server")
process.exit(0)
})
}
process.on('SIGTERM', gracefulShutdown)
process.on('SIGINT' , gracefulShutdown)
var fs = require('fs-extra')
mongoose.connect(mongoDbURI, mongoDbOptions)
var db = mongoose.connection
db.on('error', function(err){
//If the database can not be connected to, die
console.error("Error connecting to MongoDB\r\n", err)
process.exit()
})
db.once('open', function(){
//Connection successful
console.log("Successfully connected to MongoDB")
//Begin loading our schema
require('./Models/models')(mongoose, function(err, models){
//Set up the agenda piece
var Agenda = require('agenda')
models.Agenda = new Agenda()
.database(mongoDbURI, 'daemonTasks')
// Connect to the Apple Push Notification Service
models.APNAgent = require('./Modules/apnAgent')(models)
if(err){
console.log("Error loading models\r\n", err)
process.exit()
}
var async = require('async')
fs.readdir('./Daemons/', function(err, files){
if(err){
console.log(err)
cb(err)
} else {
async.each(files, function(file, cb){
fs.lstat('./Daemons/' + file, function(err, stat){
if(err){
cb(err)
} else {
if(stat.isFile()){
var daemon = require('./Daemons/' + file)(models)
agenda.define(daemon.name, daemon.options, daemon.job)
cb(null)
} else {
cb(err)
}
}
})
}, function(err){
if(err){
console.log("Error starting daemon server: ", err)
return
}
console.log("Starting daemon server")
agenda.start()
})
}
})
})
})
}
I have researched on web and found some solutions which suggest for this problem is to increase the web process time but did not find the place on Heroku where I can set this value.

socket.io client persistent retries to unreachable host

I'm trying to get a persistent connection from my socket.io-client (running on Node.js) to a remote websocket. I do not have control over the remote socket, and sometimes it can go down entirely. I would like to attempt to reconnect() whenever an error or disconnect occurs. In the following example, I'm trying to test the case where the remote host is refusing a connection. In this case, I would like to attempt to reconnect after 1 second. It calls a second time, and exits.
Here's the code:
var events = require('events'),
util = require('util'),
io = require('socket.io-client'),
url = "ws://localhost:12345", // intentionally an unreachable URL
socketOptions = {
"transports" : [ "websocket" ],
"try multiple transports" : false,
"reconnect" : false,
"connect timeout" : 5000
};
// The goal is to have this socket attempt to connect forever
// I would like to do it without the built in reconnects, as these
// are somewhat unreliable (reconnect* events not always firing)
function Test(){
var self = this;
events.EventEmitter.call(self);
var socket;
function reconnect(){
setTimeout(go, 1000);
}
function go(){
console.log("connecting to", url, socketOptions);
socket = io.connect(url, socketOptions);
socket.on('connect', function(){
console.log("connected! wat.");
});
socket.on('error', function(err){
console.log("socket.io-client 'error'", err);
reconnect();
});
socket.on('connect_failed', function(){
console.log("socket.io-client 'connect_failed'");
reconnect();
});
socket.on('disconnect', function(){
console.log("socket.io-client 'disconnect'");
reconnect();
});
}
go();
}
util.inherits(Test, events.EventEmitter);
var test = new Test();
process.on('exit', function(){
console.log("this should never end");
});
When running it under node 0.11.0 I get the following:
$ node socketio_websocket.js
connecting to ws://localhost:12345 { transports: [ 'websocket' ],
'try multiple transports': false,
reconnect: false,
'connect timeout': 5000 }
socket.io-client 'error' Error: connect ECONNREFUSED
at errnoException (net.js:878:11)
at Object.afterConnect [as oncomplete] (net.js:869:19)
connecting to ws://localhost:12345 { transports: [ 'websocket' ],
'try multiple transports': false,
reconnect: false,
'connect timeout': 5000 }
this should never end
The ECONNREFUSED is an exception you don't manage.
Try with this:
process.on('uncaughtException', function(err) {
if(err.code == 'ECONNREFUSED'){
reconnect();
}
}
Edit
Modify the options like this:
socketOptions = {
"transports" : [ "websocket" ],
"try multiple transports" : false,
"reconnect" : false,
'force new connection': true, // <-- Add this!
"connect timeout" : 5000
};
and the reconnect function (look in the comments for the explanation)
function reconnect(){
socket.removeAllListeners();
setTimeout(go, 1000);
}
Probably socket.io reuse the same connection without creating a new one, forcing it the app works

Resources