client server communication using node.js - javascript

In my client machine i have the following code
client.js
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var exec = require('child_process').exec;
var server = http.createServer(function(req, res) {
switch(req.url) {
case '/vm/list':
getVms(function(vmData) {
res.end(JSON.stringify(vmData));
});
break;
case '/vm/start':
req.on('data', function(data) {
console.log(data.toString())
exec('CALL Hello.exe', function(err, data) {
console.log(err)
console.log(data.toString())
res.end('');
});
});
break;
}
});
server.listen(9090);
console.log("Server running on the port 9090");
in my server side machine am using following helper.js
var options = {
host: '172.16.2.51',
port: 9090,
path: '/vm/start',
method: 'POST'
};
var req = http.request(options, function(res) {
res.on('data', function(d) {
console.log(d.toString());
});
});
req.on('error', function(e) {
console.error(e);
});
req.end('');
while running node helper.js am getting { [Error: socket hang up] code: 'ECONNRESET' }
it doesn’t print data.tostring() contained in the client side.

Try adding res.writeHead(200); before your switch statement.
This method must only be called once on a message and it must be called before response.end() is called.
From http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers.
Update
After our discussion the following client.js works:
var fs = require('fs');
var http = require('http');
var qs = require('querystring');
var exec = require('child_process').exec;
var server = http.createServer(function(req, res) {
switch(req.url) {
res.writeHead(200);
case '/vm/list':
getVms(function(vmData) {
res.end(JSON.stringify(vmData));
});
break;
case '/vm/start':
req.on('data', function(data) {
console.log(data.toString())
exec('CALL Hello.exe', function(err, data) {
console.log(err)
console.log(data.toString())
});
});
req.on('end', function() {
res.end('');
});
break;
}
});
server.listen(9090);
console.log("Server running on the port 9090");

Related

How can I send command line output through node.js server-sent-event and show it in browser

I am relatively new to JavaScript and I'm setting up a server sent event (sse) with node.js using some examples I see in the internet. My question is how can I send the output of the lsExample() command line function throught the res.write() function to show it in the browser.
var SSE = require('sse')
, http = require('http');
//var exec = require('child_process').exec;
var child;
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(here);
res.end('okay');
});
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function lsExample() {
const { stdout, stderr } = await exec('ls');
console.log('stdout:', stdout);
console.log('stderr:', stderr);
}
lsExample();
server.listen(8080, '127.0.0.1', function() {
var sse = new SSE(server);
sse.on('connection', function(client) {
client.send('hi there!');
});
});
Is it possible?
var http = require('http');
var SSE = require('sse');
//var exec = require('child_process').exec;
var child;
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
lsExample().then( (result)=>{
res.write(JSON.stringify(result));
res.end('');
},(err)=> {
res.write("error");
res.end('');
});
});
const util = require('util');
const exec = util.promisify(require('child_process').exec);
function lsExample() {
return new Promise(async function(resolve, reject) {
try {
const { stdout, stderr } = await exec('ls');
resolve({ "stdout" : stdout, "stderr" : stderr});
} catch (err){
reject(err);
}
});
}
server.listen(8080, '127.0.0.1', function() {
var sse = new SSE(server);
sse.on('connection', function(client) {
client.send('hi there!');
});
});

Error: socket hang up code: 'ECONNRESET' in Node.js

I am trying to post files using HTTP request on Node.js ,but after some files posted then it randomly shows
[Error: socket hang up] code: 'ECONNRESET'
My code for file sending is,
var http = require('http');
var request = require('request');
var fs= require('fs');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello World\n");
});
var serverUrl='http://localhost:3000';
function uploadFile(){
var req = request.post(serverUrl+'/api/file/upload', function (err, resp, body) {
if (err) {
console.log(err);
} else {
console.log(body);
}
});
var form = req.form();
form.append('file', fs.createReadStream('abcd.mp3'));
}
uploadFile();
server.listen(8000);

Reading data from NodeJs Serialport

I would like to be able to read data received by the ascii command sent.
Below is the code that sends command to my lock controller
var express = require('express');
var router = express.Router();
var SerialPort = require('serialport');
/* GET home page */
router.get('/', function(request, response){
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName);
console.log(port.pnpId);
console.log(port.manufacturer);
});
});
var port = new SerialPort("COM5", {
baudRate: 38400
});
port.on('open', function() {
// NodeJS v4 and earlier
port.write(new Buffer('status1', 'ascii'), function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
});
// open errors will be emitted as an error event
port.on('error', function(err) {
console.log('Error: ', err.message);
});
});
// Important
module.exports = router;
In the doc, it mentions the use of parsers to try and read data, https://github.com/EmergingTechnologyAdvisors/node-serialport#serialportparsers--object but I am not sure how to implement it, and I would want to execute after the command status1 has been written.
Essentially logs the response of the command succesfully written to the console
There are some peculiarities.
You can open port on application start and reconnect on port close or open port on each request. It defines how work with data flow. If you send request to port then answer can contain data of previous requests (more than one). You can ignore this problem (if answer is short and request interval is enough large) or send request with assign id and search answer with this id.
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName, port.pnpId, port.manufacturer); // or console.log(port)
});
});
router.get('/', function(req, res){
function sendData(code, msg) {
res.statusCode = 500;
res.write(msg);
console.log(msg);
}
var port = new SerialPort("COM5", {
baudRate: 38400
});
port.on('open', function() {
port.write(Buffer.from('status1', 'ascii'), function(err) {
if (err)
return sendData(500, err.message);
console.log('message written');
});
});
var buffer = '';
port.on('data', function(chunk) {
buffer += chunk;
var answers = buffer.split(/\r?\n/); \\ Split data by new line character or smth-else
buffer = answers.pop(); \\ Store unfinished data
if (answer.length > 0)
sendData(200, answer[0]);
});
port.on('error', function(err) {
sendData(500, err.message);
});
});
module.exports = router;

Node JS/ Socket.IO - Receive only over TCP/IP [duplicate]

I'm trying to create a dummy socket for use in some of my tests
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.write("hello!");
Getting this error
Error: This socket is closed.
I've also tried creating the socket with
var s = new net.Socket({allowHalfOpen: true});
What am I doing wrong?
For reference, the complete test looks like this
it("should say hello on connect", function(done) {
var socket = new net.Socket();
var client = Client.createClient({socket: socket});
socket.on("data", function(data){
assert.equal("hello", data);
done();
});
client.connect();
// writes "hello" to the socket
});
I don't think the server is put into listening state. This what I use..
// server
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
})
.listen(8080);
// client
var s = require('net').Socket();
s.connect(8080);
s.write('Hello');
s.end();
Client only..
var s = require('net').Socket();
s.connect(80, 'google.com');
s.write('GET http://www.google.com/ HTTP/1.1\n\n');
s.on('data', function(d){
console.log(d.toString());
});
s.end();
Try this.
The production code app.js:
var net = require("net");
function createSocket(socket){
var s = socket || new net.Socket();
s.write("hello!");
}
exports.createSocket = createSocket;
The test code: test.js: (Mocha)
var sinon = require('sinon'),
assert = require('assert'),
net = require('net'),
prod_code=require('./app.js')
describe('Example Stubbing net.Socket', function () {
it("should say hello on connect", function (done) {
var socket = new net.Socket();
var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {
console.log(data);
assert.equal("hello!", data);
done();
});
stub.on = socket.on;
prod_code.createSocket(socket);
});
});
We can create socket server using net npm module and listen from anywhere. after creating socket server we can check using telnet(client socket) to interact server.
server.js
'use strict';
const net = require('net');
const MongoClient= require('mongodb').MongoClient;
const PORT = 5000;
const ADDRESS = '127.0.0.1';
const url = 'mongodb://localhost:27017/gprs';
let server = net.createServer(onClientConnected);
server.listen(PORT, ADDRESS);
function onClientConnected(socket) {
console.log(`New client: ${socket.remoteAddress}:${socket.remotePort}`);
socket.destroy();
}
console.log(`Server started at: ${ADDRESS}:${PORT}`);
function onClientConnected(socket) {
let clientName = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`${clientName} connected.`);
socket.on('data', (data) => {
let m = data.toString().replace(/[\n\r]*$/, '');
var d = {msg:{info:m}};
insertData(d);
console.log(`${clientName} said: ${m}`);
socket.write(`We got your message (${m}). Thanks!\n`);
});
socket.on('end', () => {
console.log(`${clientName} disconnected.`);
});
}
function insertData(data){
console.log(data,'data');
MongoClient.connect(url, function(err, db){
console.log(data);
db.collection('gprs').save(data.msg , (err,result)=>{
if(err){
console.log("not inserted");
}else {
console.log("inserted");
}
});
});
}
using telnet:
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
We got your message (hi). Thanks!
you need to connect your socket before you can write to it:
var PORT = 41443;
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.connect(PORT, function(){
s.write("hello!");
});
It will useful code for websocket
'use strict';
const express = require('express');
const { Server } = require('ws');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = process.env.PORT || 5555;
const INDEX = '/public/index.html';
const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
router.get('/', function(req, res) {
res.sendFile(INDEX, { root: __dirname });
});
const server = express()
.use(router)
.use(bodyParser.json())
.use(cors)
.listen(PORT, () => {
console.log(`Listening on ${PORT}`)
});
const wss = new Server({ server });
wss.on('connection', (ws) => {
ws.on('message', message => {
var current = new Date();
console.log('Received '+ current.toLocaleString()+': '+ message);
wss.clients.forEach(function(client) {
client.send(message);
var getData = JSON.parse(message);
var newclip = getData.clipboard;
var newuser = getData.user;
console.log("User ID : "+ newuser);
console.log("\nUser clip : "+ newclip);
});
});
});

Node js displaying images from server

I am trying to display an image on a basic web page on a localhost w/ port 5000
here is main.js
var http = require('http');
var domain = require('domain');
var root = require('./root');
var image = require('./image');
function replyError(res) {
try {
res.writeHead(500);
res.end('Server error.');
} catch (err) {
console.error('Error sending response with code 500.');
}
};
function replyNotFound(res) {
res.writeHead(404);
res.end('not found');
}
function handleRequest(req, res) {
console.log('Handling request for ' + req.url);
if (req.url === '/') {
root.handle(req, res);
} else if (req.url === '/image.png'){
image.handle(req, res);
} else {
replyNotFound(res);
}
}
var server = http.createServer();
server.on('request', function(req, res) {
var d = domain.create();
d.on('error', function(err) {
console.error(req.url, err.message);
replyError(res);
});
d.run(function() { handleRequest(req, res); });
});
function CallbackToInit(){
server.listen(5000);
};
root.init(CallbackToInit);
Using callbacks I want the server to start listening(5000) only after the init function of the following code runs
var http = require('http');
var body;
exports.handle = function(req, res) {
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(body);
};
exports.init = function(cb) {
require('fs').readFile('image.png', function(err, data) {
if (err) throw err;
body = data;
cb();
});
}
It's an assignment I can't use express
I am trying to get image.png to be displayed, I think body = data doesn't work because it can't hold an image like a string? I don't want to put any HTML into my js file.
Don't roll your own app server. Use one of the great web app frameworks like express or connect.
var express = require('express');
var app = express();
app.use(express.logger());
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 5000);
Trust me, this is better.
Take a look at the node.js example for a simple http server or a tutorial/example, such as this, for serving static files through a simple server.

Categories