I was looking at this thread Secure random token in Node.js and tried to make a function:
var crypto = require('crypto');
function token() { // create a secure token
var token;
crypto.randomBytes(48, function(ex, buf) {
token = buf.toString('hex');
});
return token;
}
// more code...
var token = token();
It crashes:
Error: read ECONNRESET
at exports._errnoException (util.js:746:11)
at TCP.onread (net.js:559:26)
Any reasons to why?
"ECONNRESET" means the other side of the TCP conversation abruptly
closed its end of the connection. This is most probably due to one or
more application protocol errors. You could look at the API server
logs to see if it complains about something.
Related
I have been getting the following error, when my script stays idle for sometime. I cannot understand the reason for this.
error: [ioredis] Unhandled error event:
error: Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
error: [ioredis] Unhandled error event
error: Error: read ETIMEDOUT
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
I initialize my redis client as :
let redis = require("ioredis");
redis = Promise.promisifyAll(redis);
const redis = new redis({
host: "my hostname",
port: 6379,
password: "some password"
});
and I am using ioredis client.
Does anyone know the reason for this? The keep-alive is already enabled by default as suggested here https://github.com/luin/ioredis/blob/master/API.md
I want the client to never timeout and reconnect if the timeout occurs. I am using Redis service by azure.
We have an entire document that covers this topic: Troubleshoot Azure Cache for Redis timeouts
If using the StackExchange.Redis Client the best practice of using the following pattern is suggested:
private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
{
return ConnectionMultiplexer.Connect("cachename.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
});
public static ConnectionMultiplexer Connection
{
get
{
return lazyConnection.Value;
}
}
In the case of ioredis, you can set a client property: [options.lazyConnect]
You will also want to look at any retry methods available with your client. I hope this helps.
I have a few google cloud functions which make use of the redis memory store and it gives me this Redis connection to :6379 failed - read ECONNRESET at TCP. onread error every time any of function deployed. Previously I shared the createClient() code with all of the functions by creating a separate util file and including them on the CFs, I thought that was the issue. But please note that this Redis cache is working as expected other than this error.
Then I tried putting util code inside each of the google cloud functions which use the redis client to create the client. But I'm still getting this error from every cloud functions when every I deploy any of a cloud function. Even when deploying the functions that do not use the redis.
Here's how I create a client :
const bluebird = require('bluebird');
const redis = bluebird.promisifyAll(require('redis'));
const cache = redis.createClient({ port: REDIS_PORT, host: REDIS_HOST });
cache.on("error", (err) => {
console.log("API One - Redis cache error : " + err);
});
const list = async(data) => {
// Do something with data.
let cachedData;
if(cache.connected) {
await cache.hgetAsync(key); // Get cached Data.
}
// Do something with cached data if cachedData available.
if(cache.connected) {
await cache.hsetAsync(key, data); // Set Some Data.
}
return data;
}
module.exports = functions.https.onCall(list);
Why I'm seeing this error on every cloud function logs?
Sample error logs I get:
API One - Redis cache error : Error: Redis connection to <Ip Address>:6379 failed - read ECONNRESET
API Two - Redis cache error : Error: Redis connection to <Ip Address>:6379 failed - read ECONNRESET
Have you tried closing the redis connection before the function finishes?
The redis module may have background callbacks active during the life of the client, not closing the connection prior to function termination may be causing the connection to timeout when the cloud function terminates. Make sure that all asynchronous operations finish before the function terminates.
For example:
Example
Let me know if this works for you.
As is shown in the title, I am getting an error while establishing and connecting to a server. I am using a npm library called simple-websocket in order to achieve this.
On my server side I am using node and for my front end I am bundling the node modules using browserify. I have already tried changing the port and have searched for a fix with no results.
This is my node code:
const Server = require('simple-websocket/server')
const server = new Server({port: 8181})
new Promise((resolve, reject) => {
server.on('connection', function(socket, request) {
resolve({socket, request})
})
}).then(data => {
console.log(data)
})
This is my web code:
const Socket = require('simple-websocket')
exports.test = function() {
const socket = new Socket('wss://localhost:8181')
socket.on('connect', function() {
console.log('yes')
})
}
And This is the full error:
WebSocket connection to 'wss://localhost:8181/' failed: Error in connection
establishment: net::ERR_SSL_PROTOCOL_ERROR
bundle.js:6106 Uncaught Error: connection error to wss://localhost:8181
at WebSocket.Socket.self._ws.onerror (bundle.js:6106)
Socket.self._ws.onerror # bundle.js:6106
error (async)
Socket # bundle.js:6105
exports.test # bundle.js:2841
9../middleware-comms/Listen # bundle.js:2836
o # bundle.js:1
r # bundle.js:1
(anonymous) # bundle.js:1
In case it is useful, Here is the browserified code:
http://www.filedropper.com/bundle_2
The simple-websocket/server instance you're creating isn't listening for encrypted/wss/ssl connections, it is listening for standard websocket connections. You should be trying to connect to it with ws://localhost:8181 (not wss://...).
i have python server(with the help of asyncio and websockets module) and js client(with the help of websockets library) that are connected. The problem is that i need this connection to be secured (i'm working on passwords), but i had no success on establishing a connection with wss(web socket secure) - the code runs only with ws.
I even tried to establish my own encryption with RSA and AES but that also didn't work.
i'm really hopeles about it so if anyone ever did it or know a little about it, pls help me figure out what's wrong with it, or a direction to a rigth solution for secured connection that will work.
here's my server:
async def app(websocket, path):
while True :
data = await websocket.recv()
if (data== "close"):
print("connection with client closed.")
break
data = data.encode()
arr = data.split("~".encode())
for i in range(0,4):
arr[i]=arr[i].decode()
resualt=algo(arr)
await websocket.send(resualt)
start_server = websockets.serve(app, '0.0.0.0', 6169)
and my client:
var socket = new WebSocket("ws://127.0.0.1:6169/");
socket.onopen = function (evt) {
socket.send(st);
};
socket.onmessage = function (evt) {
alert("scrool extension page down to see the password");
$('#res').val(evt.data);
socket.send("close");
};
socket.onerror = function (evt) {
alert("the error is: "+evt.data);
};
in the python script we tried to use ssl:
c = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
c.load_default_certs(purpose=ssl.Purpose.CLIENT_AUTH)
start_server = websockets.serve(app, '0.0.0.0', 6169, ssl=c)
and in the js sciprt we wrote instead of the ws, wss:
"ws://127.0.0.1:6169/")
and the error we get:
WebSocket connection to 'wss://127.0.0.1:6169/' failed: Error in connection
establishment: net::ERR_CONNECTION_CLOSED
I am an old PERL coder trying to learn node.JS programming. I have question about the code I am writing to create a socket connection between a server and a client app.
The code below works. But I do not know how to accept data sent from the client to the server.
Basically what I want to do is very simple. Client connects to a Server listening on a socket, sends some information, which the Server reads and then sends information back to the Client. The only part I am not understanding is how to get the Server side to read/accept/display the data string sent from the Client.
Can someone please point me in the right direction?
Thank you for your help in advance.
(My apologies for being ignorant.)
Here is the server side code:
var net = require('net');
var server = net.createServer(function(socket) {
// confirm socket connection from client
console.log((new Date())+'A client connected to server...');
socket.on('data', function(data) {
var json = JSON.parse(data.toString());
console.log(json)
});
// send info to client
socket.write('Echo from server: NODE.JS Server \r\n');
socket.pipe(socket);
socket.end();
console.log('The client has disconnected...\n');
}).listen(10337, '192.168.100.1');
Here is the client code:
var net = require('net');
var client = new net.Socket();
client.connect(10337, '192.168.100.1', function() {
console.log('Connected'); // acknowledge socket connection
client.write('Hello, server! Love, Client.'); // send info to Server
});
client.on('data', function(data) {
console.log('Received: ' + data); // display info received from server
client.destroy(); // kill client after server's response
});
client.on('close', function() {
console.log('Connection closed');
});
I get an error on the server when I do this where it says the string sent from the client is an invalid token. here is the error message.
undefined:1
Hello, server! Love, Client.
^
SyntaxError: Unexpected token H
at Object.parse (native)
at Socket.<anonymous> (/root/nodejs/server-example.js:7:19)
at Socket.emit (events.js:117:20)
at Socket.<anonymous> (_stream_readable.js:765:14)
at Socket.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:427:10)
at emitReadable (_stream_readable.js:423:5)
at readableAddChunk (_stream_readable.js:166:9)
at Socket.Readable.push (_stream_readable.js:128:10)
at TCP.onread (net.js:529:21)
I was being stupid. I found the answer I was looking for. And it was very simple.
Here is what I should have written in place of the JSON statements
socket.on('data', function(data) {
var string = (data.toString());
console.log(string)
});
or handle both JSON and Strings that get written to the socket:
socket.on('data', function(data) {
try {
var obj = JSON.parse(data.toString())
console.log(JSON.stringify(obj, null, 4))
}
catch(e) {
var string = data.toString()
console.log(string)
}
})