I'm using electron-vue build an APP. I need create a tcp connection, and I use net.Socket().But i get a no response when I set HOST.
I need use the socket global, so I create a class like this:
import crc16ccitt from 'crc/crc16ccitt';
const net = require('net');
class TcpClient {
tcp = null;
alive = false;
connect(options) {
return new Promise((resolve, reject) => {
this.tcp = new net.Socket();
this.tcp.connect(options, () => {
this.alive = true;
resolve();
console.log('connect server');
});
this.tcp.on('close', () => {
this.alive = false;
console.log('close');
reject();
});
this.tcp.on('error', () => {
console.log('error');
});
});
}
}
export default TcpClient;
and then I put it in the main.js like this:
Vue.prototype.$tcp = new TcpClient();
but when I use in vue instance like this:
this.$tcp.connect({ port: 8000, host: 127.0.0.1 });
Nothing happend, no errors, no result, but when I reload my page, I think connect a moment, and my server shows:
events.js:174
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
And if I don't set HOST, just port, it works well.
Related
When I call the createFile() function in my Cypress test, I am trying to create a file on a hosted SFTP server.
Currently, when I call it, I get the following error message:
The following error was thrown by a plugin. We stopped running your tests because a plugin crashed. Please check your plugins file (C:\Dev\SFTP_POC\cypress\plugins\index.js)
Error: put: Internal server error.
sftp://myHost.com#sftp.next.rec-test.com:2022/reports/
at fmtError (C:\Dev\SFTP_POC\node_modules\ssh2-sftp-client\src\utils.js:55:18)
at WriteStream. (C:\Dev\SFTP_POC\node_modules\ssh2-sftp-client\src\index.js:728:18)
at Object.onceWrapper (events.js:418:26)
at WriteStream.emit (events.js:323:22)
at Object.cb (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\SFTP.js:3629:12)
at 101 (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\SFTP.js:2622:11)
at SFTP.push (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\SFTP.js:278:11)
at CHANNEL_DATA (C:\Dev\SFTP_POC\node_modules\ssh2\lib\client.js:525:23)
at 94 (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\handlers.misc.js:859:16)
at Protocol.onPayload (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\Protocol.js:2025:10)
at AESGCMDecipherNative.decrypt (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\crypto.js:987:26)
at Protocol.parsePacket [as _parse] (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\Protocol.js:1994:25)
at Protocol.parse (C:\Dev\SFTP_POC\node_modules\ssh2\lib\protocol\Protocol.js:293:16)
at Socket. (C:\Dev\SFTP_POC\node_modules\ssh2\lib\client.js:713:21)
at Socket.emit (events.js:311:20)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
Below is my current index.js code:
module.exports = (on, config) => {
on('task', {
createFile() {
const fs = require('fs');
let data = fs.createReadStream('C:/Dev/SFTP_POC/cypress/fixtures/example.json');
let remote = 'sftp://myHost.com:2022/reports/';
let Client = require('ssh2-sftp-client');
let sftp = new Client();
const config = {
host: 'myHost.com',
port: '2022',
username: 'myUsername',
password: 'myPassword'
};
sftp.connect(config).then(() => {
sftp.put(data, remote);
})
.then(data => {
console.log('Success');
})
.then(() => {
sftp.end();
})
.catch(err => {
console.log(err);
})
return null;
}
})
}
My remote variable is a folder that exists on the server.
However, after the test, a new file isn't being added.
Can someone please tell me what I'm doing wrong here, & how to resolve it
The class:
const mysql = require('mysql');
module.exports = function () {
this.connection = mysql.createConnection({
host : 'localhost',
user : 'USER',
password : 'PASSWORD',
database : 'DATABASE',
multipleStatements: true
});
this.query = (sql, args) => {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err );
resolve( rows );
});
});
};
this.close = () => {
return async () => {
try {
this.connection.end(err => {
if (err) throw err;
return;
});
} catch(e) {
return e;
}
}
};
};
In index i call it like this:
const Database = require('./server/modules/mysql'),
connection = new Database();
The problem:
Overnight mysql crashes:
[nodemon] starting `node index.js`
listening on port 420
events.js:292
throw er; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:112:13)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:526:10)
at Socket.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:315:20)
at Protocol._delegateError (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.end (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\protocol\Protocol.js:116:8)
at Socket.<anonymous> (C:\Users\fedesc\Sites\borsalino\node_modules\mysql\lib\Connection.js:94:28)
[... lines matching original stack trace ...]
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
fatal: true,
code: 'PROTOCOL_CONNECTION_LOST'
}
[nodemon] app crashed - waiting for file changes before starting...
I'm using Nodemon and a simple restart to the application solves the issue until the next morning (or next long period of not coding.)
I'm not really using close() anywhere or after anything since in the docs it says it's not needed, just query().
but clearly i get a timeout somewhere somehow, like i should deal with the opening and closing of connection.
Do i need to close connections after making queries in my app?
Is there a way to set the timeout limit or dealing with him?
Am i just setting it up wrong or using wrong/outdated tool?
Thanks.
I have a TCP/IP device that I have written script in python to connect and receive data from and this works. I am now trying to do something similar with nodejs but keep running in to either connection errors or security issues with the buffer depending on the nodejs methods I have tried.
This is the python script that works;
import socket
import csv
import datetime
from decimal import Decimal
import time
UDP_IP = "10.0.0.122"
UDP_PORT = 1025
MESSAGE = "#01\r"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE.encode(encoding='utf-8'), (UDP_IP, UDP_PORT))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print ("received message:", str(data))
Here are 3 methods I have tried with varying errors listed in comments in js. I am new to node js and could really do with some help.
Thanks in advance
// //Method 1
// var net = require('net');
// var client = new net.Socket();
// client.connect(1025, '10.0.0.122', function() {
// console.log('Connected');
// client.write('Hello, server! Love, Client.');
// });
// client.on('data', function(data) {
// console.log('Received: ' + data);
// client.destroy(); // kill client after server's response
// });
// client.on('close', function() {
// console.log('Connection closed');
// });
//Method 2
// // Include Nodejs' net module.
// const Net = require('net');
// // The port number and hostname of the server.
// const port = 1025;
// const host = '10.0.0.122';
// // Create a new TCP client.
// const client = new Net.Socket();
// // Send a connection request to the server.
// client.connect({ port: port, host: host }), function() {
// // If there is no error, the server has accepted the request and created a new
// // socket dedicated to us.
// console.log('TCP connection established with the server.');
// // The client can now send data to the server by writing to its socket.
// client.write('#01\r');
// };
// // The client can also receive data from the server by reading from its socket.
// client.on('data', function(chunk) {
// console.log(`Data received from the server: ${chunk.toString()}.`);
// // Request an end to the connection after the data has been received.
// client.end();
// });
// client.on('end', function() {
// console.log('Requested an end to the TCP connection');
// });
//Method 1 and 2 give this error
// events.js:287
// throw er; // Unhandled 'error' event
// ^
// Error: connect ECONNREFUSED 10.0.0.122:1025
/ / at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
// Emitted 'error' event on Socket instance at:
// at emitErrorNT (internal/streams/destroy.js:92:8)
// at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
// at processTicksAndRejections (internal/process/task_queues.js:84:21) {
// errno: 'ECONNREFUSED',
// code: 'ECONNREFUSED',
// syscall: 'connect',
// address: '10.0.0.122',
// port: 1025
// }
//Method 3
var PORT = 1025;
var HOST = '10.0.0.122';
var dgram = require('dgram');
var message = new Buffer('#01\r');
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
if (err) throw err;
console.log('UDP message sent to ' + HOST +':'+ PORT);
client.close();
});
//Method 3 error
// [Running] node "c:\Users\admin\Nodejs tcp test\app.js"
// (node:6032) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability
issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
// UDP message sent to 10.0.0.122:1025
// [Done] exited with code=0 in 0.155 seconds
I have figured it with a little help from google. There are some good examples for a UDP connection in js.
With a pointer in the right direction from Rodrigoms github project,
https://github.com/rodrigoms2004/ServerSocketTCP_UDP
I managed to achieve the same as I was getting in my python file using the following code.
const udp = require('dgram')
// creating a client socket
const client = udp.createSocket('udp4')
//buffer msg
const data = Buffer.from('#01\r')
client.on('message', (msg, info) => {
console.log('Data received from server : ' + msg.toString())
console.log('Received %d bytes from %s:%d\n', msg.length, info.address, info.port)
})
//sending msg
client.send(data, 1025, '10.0.0.122', error => {
if (error) {
console.log(error)
client.close()
} else {
console.log('Data sent !!!')
}
})
setTimeout( () => {
client.close()
},1000)
I have a Heroku server with node.js and express that pings a website's API every second. This works fine for hours at a time, but every once in a while I'll get this error:
2018-01-10T02:19:28.579566+00:00 app[web.1]: events.js:141
2018-01-10T02:19:28.579578+00:00 app[web.1]: throw er; // Unhandled 'error' event
2018-01-10T02:19:28.579579+00:00 app[web.1]: ^
2018-01-10T02:19:28.579581+00:00 app[web.1]:
2018-01-10T02:19:28.579582+00:00 app[web.1]: Error: connect ETIMEDOUT 45.60.11.241:443
2018-01-10T02:19:28.579583+00:00 app[web.1]: at Object.exports._errnoException (util.js:907:11)
2018-01-10T02:19:28.579584+00:00 app[web.1]: at exports._exceptionWithHostPort (util.js:930:20)
2018-01-10T02:19:28.579585+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)
2018-01-10T02:19:28.684990+00:00 heroku[web.1]: Process exited with status 1
Sometimes the error is ETIMEDOUT but sometimes it's other things (can't remember right now).
Some other post I read made me think maybe this is a problem?
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
})
Or maybe it's the part inside the API call loop?
try
{
async.series([
function(callback) {
apiQuery( callback, method, params);
},
], function(error, results) {
console.log(results)
});
}
catch(e)
{
console.log("something went wrong!")
}
Not sure why the try catch isn't catching the error if it's this.
Maybe it's how I'm starting the loop?
runLoop()
//start looping the api data pulls
function runLoop() {
setInterval(apiLoop, 1000)
}
Would it be better to have apiLoop call itself in the callback function? Or would that create nested functions that keep using increasingly larger memory?
Here is the api call code:
function apiQuery( callback2, method, params )
{
if ( ! params ) params = [];
var host_name = 'www.host.com';
var url = '/Api/' + method;
if ( params ) url += "/" + params.join('/');
var options = {
host: host_name,
path: url,
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
return callback2(null, str);
});
}
https.request(options, callback).end();
}
Maybe ETIMEOUT is caused by the website's server, anyway you can catch the error
const req = https.request(options, callback)
req.on('error', (e) => {
console.error(e);
});
req.end();
I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev