After a few minutes of inactivity Node Redis always throws read ETIMEDOUT error and stops the application.
Using simple expess.js application and redis client.
redis.createClient({
url: "redis://default:user#123.123.12.123:6379"
});
After different tries to figure out what's wrong I have found a solution to add pingInterval option to Redis config, so the connection is always alive.
This config fixed my issue:
redis.createClient({
url: "redis://default:user#123.123.12.123:6379",
pingInterval: 1000 // <- add pingInterval
});
Related
I have created a server using net module:
// Creating and connecting with server
const net = require('net');
const server = net.createServer(); //Creating server
//Connecting with server
server.on('connection', function (socket) {
let remoteAddress = `${socket.remoteAddress},${socket.remotePort}`
console.log(remoteAddress)
console.log(`connection is established... ${Date.now()} \n `);
socket.write(`connection is established...${Date.now()} \n`);
//Receiving and Sending payload from/to client
socket.on('data', async function (payload) {
console.log("payload from client",payload)
socket.write(`acknowledge : ${payload}`);
});
//Close connection
socket.on('close', function () {
console.log('Server Connection Closed');
});
//Server error
socket.on('error', function (err) {
console.log("Caught flash policy server socket error: ")
console.log(err.stack)
});
});
server.listen(8001, function () {
console.log('Server Listing on Port 8001');
})
I deploy this code to AWS EC2 and When I tried to connect with telnet client (telnet ec2_ip 8001), initailly it is working but after sometime it is giving following errors.
screenshot of telnet client:
screenshot of ec2 logs:
And When I tried to connect with real IOT scooter with ec2 Ip address and port 8001, It is not connecting for even a second.
Can anyone please tell me what I am doing wrong?
Note: I don't have much knowledge about IoT. This is the first time I am connecting an IoT scooter with nodejs.
It is hard to know exactly what your problem is without seeing more of your code, or getting more explained. Like what happens in your real code? The logs seem to indicate that you are making outbound calls to another service after the initial connection. If that is the case, are you handling error conditions of your dependencies correctly? An unhandled exception would kill your server, and it would need to be restarted to work again. If you are using dependencies that fail, for instance databases, other servers, configuration files etc that fail on your scooter, that may be why it fails without even allowing one single connection. But without knowing more specifics about your application and architecture, it is just wild guesses at this point.
Your server example code, seems fine. As long as you have opened for traffic on that port in your routing configuration in AWS, it should respond. It could be that you just simply run out of connections, but again that requires me to know more to give you a definitive answer.
My advice would be to check your dependencies, and your logs for supporting systems.
I'm currently trying to build a simple CRUD API using Node.js with Express. I usually have no trouble, but today, a new error message started to appear.
I can use a TCP Port once. If the server stops and restart, it gives me this error:
Error: listen EADDRINUSE: address already in use 3111;
I can change the port, but can only use the new one once. The code giving me this is the following:
// Load packages
const express = require("express");
const formidable = require("express-formidable");
const mongoose = require("mongoose");
const cors = require("cors");
// Initialize serve;
require("dotenv").config();
const mongoURL = process.env.DATABASE_URI;
const app = express();
app.use(formidable());
app.use(cors());
// Connect to the database
mongoose.connect(`${mongoURL}/Some_database`, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Get all non-existent routes
app.all("*", (req, res) => {
res.status(404).json({ message: "Ressource not found" });
});
// Launch server
app.listen(process.env.PORT, () => {
console.log("Server launched");
});
I launch the server using npx nodemon index.js.
I've already tried to get the process ID using the asked port with sudo lsof -i tcp:3111, as well as killall -9 node, but I don't get anything with these command, the last one only returns No matching processes belonging to you were found.
EADDRINUSE means that the port number which listen() tries to bind the server to is already in use.
So, in your case, there must be running a server on port 3111 already.
search for process id:
sudo lsof -i :3111
this will list all the PIDs listening on this port, once you have the PID , you can terminate it with the following:
kill -9 {PID}
restart your server.
Hello and thank you for the answer, Barrios. Sorry for this really delayed response.
I found the solution last week; for people who could get stuck with the same issue, I will start with answering the comments. First, I am working with MacOS Big Sur 11.2.3.
I tried the sudo lsof -i :3111 before posting, but no server was found on this port, I couldn't find an ID to terminate with kill -9 command.
Well, as often, the cause was very simple, I must have messed up when initializing my projet with npm init -y and no node_module repertory was created, each time I would launch my server, a hidden file would be created with the port number as its name and as long as it was there, I couldn't use the associated port.
Sorry for wasting time with this issue.
I'm developing a web app using express, and MySQL. I was able to publish the app on heroku for testing. The problem came after few minutes or seconds, the server throws the following error:
Error: Connection lost: The server closed the connection.
at Protocol.end (/app/node_modules/mysql/lib/protocol/Protocol.js:112:13)
at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:94:28)
at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:526:10)
at Socket.emit (events.js:327:22)
When I restart the server, I'm able to execute some successful calls to database, but after some minutes, the connection get lost.
This is the connection file I'm currently using, I will, change my credentials for placeholders, only for security purppose.
module.exports = {
HOST: 'mysql5044hostname',
USER: 'myUserName',//root
PASSWORD: 'thisIsMyPassword',
DB: 'default_schema'
};
Any help regarding this matter, will be appreciated.
#vodolaz095 and #riscarrott thanks to both of you, I changed the logic based on the documentation you sent, and I was able to successfully connect to database without losing the communication with the server.
I have been trying to get my WAMP Webserver run with socket.io but I just cannot seem to get it to work.
My socket server is on port 3000 and the WAMP on port 80. I know that both servers work.
Web Server Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://[ip address]:3000');
socket.on('buzz', function (data) {
console.log(data);
});
</script>
Console Error:
Uncaught ReferenceError: io is not defined
at (index):97
UPDATE
I was missing the socket.io.js file. But now I am getting
GET http://[[IP]]:3000/socket.io/?EIO=3&transport=polling&t=LxfQwpE
net::ERR_CONNECTION_TIMED_OUT
In the console every few seconds.
As I recall, this problem was solved by installing a NGINX reverse proxy -- I believe I followed the instructions here: Socket.io with nginx
This was one of my first projects, but I thought I would point people in the right direction in case other students wish to use a WAMP backend and Socket.io.
I'm trying to run socket.io and I'm getting a bunch of these:
http://domain.com:8080/socket.io/?EIO=2&transport=polling&t=1401421022966-0 400 (Bad Request)
This is the response I'm getting:
{"code":0,"message":"Transport unknown"}
I can't find any reason. I read somewhere that it might be misinterpreting the client, but that's about as far as I could get.
I had the same issue after upgrading from 0.9.x to 1.x.x. Shortening the long story, I would set transports to ['websocket', 'polling'] and then the error...
when you config your server to use specefic transpors you should set the same config on client side to...
server
var io = require('socket.io')(server, {'transports': ['websocket', 'polling']});
client
var io = io( serverUri, {'transports': ['websocket', 'polling']});
I had the same issue,after upgrading from 0.9.x, turns out my server config was set to ['websocket', 'jsonp-polling'] which was valid in 0.9 but the default config for the client and server is now ['polling', 'websocket'].
Removing my server config got me up and running.
The config is now documented in engine.io (https://github.com/automattic/engine.io), the new transport layer introduced in 1.0 - in particular this line:
transports ( String): transports to allow connections to (['polling', 'websocket'])
i had the same issue:
Getting the latest socket-client.js and using these file on clientside, solved this problem for me.
This happened to me when I served the socket.io.js script myself.
I had to go copy node_modules/socket.io/node_modules/socket.io-client/socket.io.js to where I was serving it up.
Try this configuration on server side
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:8100",
methods: ["GET", "POST"],
transports: ['websocket', 'polling'],
credentials: true
},
allowEIO3: true
});
My solution was to upgrade node.js to latest (0.12.0 at the time of this post). Originally node.js was installed as a part of a bundle. Once I uninstalled that node.js coming from that bundle (Aptana 3 bundle, node.js was somewhat behind), and installed the latest from node.js's website, things started working finally.
I was experimenting with React.js. I spent several hours debugging the phenomena, I've found build errors in socket.io, specifically about socket.io-client, it tried to invoke Visual Studio MSBuild unsuccesfully. Which is sad, the error occured with node-gyp too. Apparently socket.io-client is not needed to run/serve my examples, and seems like these unfortunate errors (which lured me into an endless forest) can be ignored.
(I noticed also a module while installing webpack-dev-server, which is Darwin only (a.k.a. Mac OS X). That's fortunately an optional dependency. It's frightening though: I know that Apple is very hipster, but the majority of the world is non Mac.)
I fixed it acting in my server.js
the io instance is initialized as follow:
const io = socket.listen(httpServer, { serveClient: true })
Before I had { serveClient: false }, because otherwise, I was getting an error. But actually, if you want that your client takes io from the node instance you have to serve it.
UPDATE: At the end.. you want to simply have const io = socket.listen(httpServer)
In this way is going to be true by default.