I have a TCP server that receive messages from a IOT device. When a message is received, my TCP server send it to my REST server via HTTP. But after the first request is successfully send, when the TCP server want to send the second message, I get a write after end error.
This is my Code on the TCP server:
const net = require("net");
const server = net.createServer(onConnected);
const http = require("http");
const querystring = require('querystring');
//HTTP STUFF
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding("utf8");
res.on("data", (chunk) => {
console.log(`BODY: ${chunk}`);
})
res.on("end", () => {
console.log("no more data in res");
})
});
req.on("error", (err) => {
if (err.code === "ETIMEDOUT") {
console.log("problem with request: connection timeout");
} else if (err.code === "ECONNRESET") {
console.log("problem with request: read timeout");
} else {
console.error(`problem with request: ${err.message}`);
}
});
function send(postData) {
console.log("start http");
console.log("post data: " + postData);
req.write(postData, function() {
req.end();
});
};
//TCP
server.listen(PORT, HOST, function() {
console.log("Server listening on &j", server.address());
});
function onConnected(sock) {
var remoteAddress = sock.remoteAddress + ":" * sock.remotePort;
console.log("new client connected: %s", remoteAddress);
sock.on("data", function(data) {
console.log("%s says: %s", remoteAddress, data);
let tcp_message = data.toString("utf8");
let postData = querystring.stringify({
"message": tcp_message
});
console.log("tcp message " + tcp_message)
options.headers = {'Content-Length': Buffer.byteLength(postData) }
send(postData);
let mail_text = "Address: " + remoteAddress + " data: " + tcp_message;
});
sock.on("close", function(){
console.log("connection from %s closed", remoteAddress);
});
server.on("error", function(err){
console.log("connection %s error: %s", remoteAddress, err.message);
});
}
Related
Below is my jasmine test code.
const https = require('http');
var base_url = "http://localhost:3000/";
function testAsync(){
return new Promise((resolve, reject)=>{
https.get(base_url, res => {
console.log("result is : " + res);
let data = [];
const headerDate = res.headers && res.headers.date ? res.headers.date : 'no response date';
console.log('Status Code:', res.statusCode);
console.log('Date in Response header:', headerDate);
res.on('data', chunk => {
console.log("inside data : " +data);
data.push(chunk);
});
res.on('end', () => {
console.log("data" + data);
// console.log('Response ended: ');
// const users = JSON.parse(Buffer.concat(data).toString());
// for(user of users) {
// console.log(`Got user with id: ${user.id}, name: ${user.name}`);
// }
});
resolve();
}).on('error', err => {
console.log('Error: ', err);
resolve();
});
});
}
describe("Hello World Server", function() {
describe("GET /", function() {
it("returns status code 200", async function() {
console.log("before http get");
await testAsync();
console.log("after http get");
});
});
});
when I run it, I get the below error. Could someone help to resolve this error please
LOG: 'before http get'
LOG: 'Error: ', TypeError: Failed to fetch
TypeError: Failed to fetch
at module.exports.ClientRequest._onFinish (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:8593:10)
at module.exports. (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:8511:8)
at module.exports.emit (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:2692:5)
at finishMaybe (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:7444:14)
at endWritable (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:7463:3)
at module.exports.Writable.end (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:7391:22)
at module.exports.ClientRequest.end (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:8763:32)
at Object.get (http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:8343:6)
at http://localhost:9876/absolute/var/folders/s7/lslgtwnx2px86cqjhlfynp_w0000gn/T/3e973e3340db6a2c56d8e559cc233f06.browserify.js?9dffcbb6a2ae2b7cbde165353439c6209f6eaf5f:10878:13
at new Promise ()
LOG: 'after http get'
I included the socket.io.js in client and also included the custom created socket.js for getting the responses from websocket server to client,when i loading this page in browser automatically stopped the websocket server and in browser console tells WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=3&transport=websocket&sid=2p1ZYDAflHMHiL70AAAA' failed: Connection closed before receiving a handshake response
user defined socket.js code is given below
var socket = io();
var actionItems = []
var beginTakingAction = false
var strOut;
socket.on('transcript', function(x) {
var div = $('div.transcription')
div.html(x);
console.log("transcript " + x);
if (!scrolling) {
div.scrollTop(div[0].scrollHeight);
}
})
socket.on('action', function(x) {
console.log('sending action',x);
actionItems.push(x)
$('div.action').html(actionItems[actionItems.length-1]);
})
socket.on('sentiment', function(x) {
sentimentChart.update(x)
})
socket.on('nlp', function(x) {
wordLengthDistChart.update(x.wordLenghDist);
posTagDistChart.update(x.posTagDist);
})
socket.on('keywords', function(x) {
keywordChart.update(x)
})
socket.on('status', function(status) {
$('div.status').html("status: " + status);
if (status == "connected") {
sentimentChart.reset()
keywordChart.reset()
wordLengthDistChart.reset()
posTagDistChart.reset()
$('div.transcription').html('');
}
})
please give any suggesstions??
my server code is given below
require('dotenv').config()
var WebSocketServer = require('websocket').server;
var http = require('http');
var HttpDispatcher = require('httpdispatcher');
var dispatcher = new HttpDispatcher();
const fs = require('fs');
const winston = require('winston')
winston.level = process.env.LOG_LEVEL || 'info'
var AsrClient = require('./lib/asrClient')
var asrActive = false
var myAsrClient;
var engineStartedMs;
var connections = []
//Create a server
var server = http.createServer(function(req, res) {
handleRequest(req,res);
});
// Loading socket.io
var io = require('socket.io').listen(server);
// When a client connects, we note it in the console
io.sockets.on('connection', function (socket) {
winston.log('info','A client is connected!');
});
var wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true,
binaryType: 'arraybuffer'
});
//Lets use our dispatcher
function handleRequest(request, response){
try {
//log the request on console
winston.log('info', 'handleRequest',request.url);
//Dispatch
dispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}
dispatcher.setStatic('/public');
dispatcher.setStaticDirname('public');
dispatcher.onGet("/", function(req, res) {
winston.log('info', 'loading index');
winston.log('info', 'port', process.env.PORT)
fs.readFile('./public/index.html', 'utf-8', function(error, content) {
winston.log('debug', 'loading Index');
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
// Serve the ncco
dispatcher.onGet("/ncco", function(req, res) {
fs.readFile('./ncco.json', function(error, data) {
winston.log('debug', 'loading ncco');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(data, 'utf-8');
});
});
dispatcher.onPost("/terminate", function(req, res) {
winston.log('info', 'terminate called');
wsServer.closeAllConnections();
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end();
});
wsServer.on('connect', function(connection) {
connections.push(connection);
winston.log('info', (new Date()) + ' Connection accepted' + ' - Protocol Version ' + connection.webSocketVersion);
connection.on('message', function(message) {
if (message.type === 'utf8') {
try {
var json = JSON.parse(message.utf8Data);
winston.log('info', "json", json['app']);
if (json['app'] == "audiosocket") {
VBConnect();
winston.log('info', 'connecting to VB');
}
} catch (e) {
winston.log('error', 'message error catch', e)
}
winston.log('info', "utf ",message.utf8Data);
}
else if (message.type === 'binary') {
// Reflect the message back
// connection.sendBytes(message.binaryData);
if (myAsrClient != null && asrActive) {
winston.log('debug', "sendingDate ",message.binaryData);
myAsrClient.sendData(message.binaryData)
}
}
});
connection.on('close', function(reasonCode, description) {
winston.log('info', (new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
wsServer.closeAllConnections();
});
});
wsServer.on('close', function(connection) {
winston.log('info', 'socket closed');
if (asrActive) {
io.sockets.emit('status', "disconnected");
winston.log('info', 'trying to close ASR client');
myAsrClient.close();
myAsrClient = null;
asrActive = false;
}
else {
winston.log('info', 'asr not active, cant close');
}
})
wsServer.on('error', function(error) {
winston.log('error', 'Websocket error', error);
})
var port = process.env.PORT || 8000
server.listen(port, function(){
winston.log('info', "Server listening on :%s", port);
});
I was using net module to build a simple server/client example. The client side just send a simple message after connection is built, and server side didn't do anything but just print some log, but after that I found the data event in client side got triggered, and the data received is the data it send to the server (but server didn't write anything to client).
Client.js:
var net = require('net');
var port = 3540;
var hostName = "127.0.0.1";
var client = new net.Socket();
client.connect(port, hostName, function() {
console.log("Connected to the remote host: " + hostName + ":" + port);
client.write("hello,world");
client.end();
});
var bytesReceived = 0;
client.on('data', function(data) {
bytesReceived += data.length;
console.log('Received bytes: ' + data.length + ', total bytes received: ' + bytesReceived);
console.log(data.toString())
})
client.on('error', function(error) {
console.log(error);
client.destroy();
});
client.on('close', function() {
console.log('Closed connection');
})
server.js:
var net = require('net');
port = 3540;
var log = function(who, what) {
return function() {
var args = Array.prototype.slice.call(arguments);
console.log('[%s on %s]', who, what, args);
};
};
var count = 0
var echo = function (socket) {
socket.on('end', function() {
console.log('recevied a FIN packet');
socket.end();
});
socket.on('data', function(data) {
console.log(count + ': received bytes: ' + data.length);
count++;
});
socket.on('error', function(error) {
console.log(error);
socket.destroy();
});
socket.on('close', function() {
console.log('connection has been closed!');
});
socket.pipe(socket);
}
var server = net.createServer(echo);
server.listen(port); // port or unix socket, cannot listen on both with one server
server.on('listening', function() {
var ad = server.address();
if (typeof ad === 'string') {
console.log('[server on listening] %s', ad);
} else {
console.log('[server on listening] %s:%s using %s', ad.address, ad.port, ad.family);
}
});
server.on('connection', function(socket) {
server.getConnections(function(err, count) {
console.log('%d open connections!', count);
});
});
server.on('close', function() { console.log('[server on close]'); });
server.on('err', function(err) {
console.log(err);
server.close(function() { console.log("shutting down the server!"); });
});
After that the client print out:
Connected to the remote host: 127.0.0.1:3540
Received bytes: 11, total bytes received: 11
hello,world
Closed connection
but server didn't write anything to client
It does:
socket.pipe(socket)
This will echo the data received from the client (represented by socket) back to the client.
I have a larger process running through a large collection of locations/devices in an API response and I'm trying to get to individual devices and turn that into a response my target system will understand. However it seems my inline HTTP request is not firing.
I've tried moving the callback out of the 'end' event, but I'm not even getting the logging for earlier up in the function. The only logging output I get is the "getting status for zone xyz"
async.each(tempSystem.zones, function(zone, zoneCallback) {
var applianceDiscovered = {};
console.log("getting status for zone", zone);
var options = {
host: host,
path: '/webapi/' + zone.zoneId + '/status',
headers: {'Authorization' : 'Bearer ' + accessToken}
};
var req = https.get(options, function(res) {
if (res.statusCode != 200) {
console.log("error ", res.statusCode);
}
console.log(res);
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
});
res.on('end', function() {
if (res.statusCode === 200) {
console.log("get zone status: ", res.statusCode);
var body = Buffer.concat(bodyChunks);
var zoneStatus = JSON.parse(body);
console.log(zoneStatus);
zoneCallback();
} else {
console.log(res.statusCode);
}
});
res.on('error', function(error) {
console.log(error);
});
});
req.on('error', function(e) {
console.log("error: ", e);
});
}, function(err){
console.log("finished with zones");
});
If a server is not responding, how can I retry the connect?
I get the error ECONNREFUSED, but I want to retry the connection at least 5 times.
Here is my code:
var body = JSON.stringify(saveObj);
var request = http.request({
host: BASE_URL,
port: PORT,
path: LINK_SAVE,
url : 'https://coherent-bay-777.appspot.com/_ah/api/timesOfIndia/v1/addChannel',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body)
}
}, function(res) {
var resp = '';
res.on('data', function(data) {
resp += data;
});
res.on('end', function() {
resp = JSON.parse(resp);
if(resp.id) {
winston.info(resp.id);
saveObj.update({$set : { id : resp.id }},
function(err) {
if(err) {
winston.error(err);
} else {
cb();
}
});
} else {
cb();
}
});
res.on('error', function(err) {
winston.error(err);
//cb();
});
winston.info('Request Ended');
});
if(body == '{}') {
cb();
return;
}
request.on('socket', function (socket) {
socket.setTimeout(15000);
socket.on('timeout', function() {
console.log("Timeout, aborting request")
request.abort();
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
error callback will receive a "socket hang up" on timeout
});
request.write(body);
request.end();