Sending data from client to server in Node.js - javascript

I'm trying to write a simple client-server program in Node.js where the client will enter 2 arguments (for example, user will type S 4 to get the value of the square root of 4) for a mathematical computation, send it to the server, and the server will return the answer. It works for the most part; however, when the server returns the answer, the client displays the answer and also displays the original input. Can anyone point out why this is happening?
server.js
var net = require('net');
var server= net.createServer(function(c) {
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.on('data', function(data) {
data = data.toString().split(" ");
var num = parseInt(data[1], 10);
switch (data[0]){
case 'S':
c.write(Math.sqrt(num).toString());
}
});
c.write('What would you like to do?\n');
c.write('(S) - Square root <arg>\n');
c.pipe(c);
});
server.listen(3000, function() {
console.log('server bound');
});
client.js
var net = require('net');
var num = 1;
var client = net.connect({port:3000}, function() {
console.log('client connected');
});
client.on('data', function(data) {
if (num == 1) {
console.log(data.toString());
process.stdin.resume();
process.stdin.once('data', function(input) {
client.write(input);
});
num++;
} else {
console.log("Server returned: " + data.toString() + "\n");
process.exit();
}
});
client.on('end', function() {
console.log('\nclient disconnected\n');
});
To clarify: when I input S 4 in the client, the result printed to the screen is Server returned: 2S 4

You are piping the input to the output

Related

Cannot connect or emit to Amazon ECS Socket.io Server via Socket.io from a HTML file located in S3 bucket

I am having trouble connecting and emitting to an ECS Fargate Socket.io Server on AWS via Socket.io from a HTML file located in a S3 bucket in the same AWS region.
The ECS Fargate Server's code is as follows:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var AWS = require ('aws-sdk');
io.on('connect', function (socket){
console.log('connection made');
socket.on('disconnect', function (socketds) {
console.log("***********************************************");
console.log("Disconnected");
});
socket.on('reconnect', function (socketds) {
console.log("***********************************************");
console.log("Reconnected");
});
socket.on('c_status', function () {
console.log("*********************************************");
console.log("cstatus");
});
socket.on('app_message', function (mdata) {
console.log("***********************************************");
console.log("App-message:",mdata);
socket.emit('command1',mdata);
});
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
And the relevant code of the HTML file is as follows:
<script>
const serverLocation = "http://application-load-balancer-dns-link:3000";
const socket = io(serverLocation);
function sendmsg() {
var date = new Date();
date.setHours(date.getHours() + 4);
var datetm = date.toISOString().split('.')[0]+"Z";
var node_id = $('#innode').val();
var clid = "0";
var msg = $('#message').val();
if (node_id.length === 1) {
var unitcode = "0" + "0" + node_id;
}
else if (node_id.length === 2) {
var unitcode = "0" + node_id;
}
else {
var unitcode = node_id;
}
var mdata = datetm+unitcode+msg;
socket.emit('app_message',mdata);
}
</script>
I have been at it for 2 days now and have not been able to figure it out. It just doesn't connect.
Any help is greatly appreciated.
If you need more information, please let me know.
1) Try checking the inbound rules of the security group associated with that instance.
2) Outbound rules should also be configured as its bidirectional (By Default allows all)
3) If they are perfect. Check whether timeout occurs or any other exception.

TypeError: serialport.parsers.readline is not a function

I am trying to run this program in Raspberry Pi 3.
I have installed nodejs and ws on my raspberry pi.
Then I installed serial port module.
I am trying to create this project:enter link description here
I have tried to find solutions everywhere but I could not find one.
If any one knows how to solve this problem please help me.
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "5bb3ba9304674086bee67fa507a215cf"; //DEVICE ID
var device_token = "36b278345b6d4d11abf764ae213c5c70"; //DEVICE TOKEN
var WebSocket = require('ws');
var isWebSocketReady = false;
var data="";
var ws = null;
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", { //for serial communication with arduino
baudrate: 9600,
// The baud rate of uno is 9600
parser: serialport.parsers.readline("\n")
});
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket connection and setup GPIO pin
*/
function start() {
//Create the WebSocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("WebSocket connection is open ....");
register();
});
ws.on('message', function(data) {
//this loop is called whenever the client sends some message
handleRcvMsg(data); //data is send to the function handleRcvMsg()
});
ws.on('close', function() {
console.log("WebSocket connection is closed ....");
});
}
/**
* Sends a register message to /websocket endpoint
*/
//Client will only work when device gets registered from here
function register(){
console.log("Registering device on the WebSocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
//data after receiving is sent here for processing
function handleRcvMsg(msg){
var msgObj = JSON.parse(msg);
if (msgObj.type != "action") return; //Early return;
var actions = msgObj.data.actions;
var actionName = actions[0].name; //assume that there is only one action in actions
console.log("The received action is " + actionName);
}
/**
* Send one message to ARTIK Cloud
*/
//This function is responsible for sending commands to cloud
//function sendStateToArtikCloud(parking,temperature,water){
function sendDataToArtikCloud(pantry){
var result=pantry.split(" ");//data gets split by " " to get the values
try{
ts = ', "ts": '+getTimeMillis();
var data = {
"Garlic": result[1],
"Potato":result[2],
"Temperature":result[3],
"Chilli":result[4],
"Humidity": result[5],
"Ginger":result[6],
"Onion": result[7]
};
var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload + '\n');
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString() +'\n');
}
}
function exitClosePins() {
console.log('Exit and destroy all pins!');
process.exit();
}
start();
//exectes every second when data is received from arduino (5sec programmed delay from arduino)
sp.on("open", function () {
sp.on('data', function(data) {
console.log("Serial port received data:" + data);
//var result=data.split(" ");//data gets split by " " to get the values
//sendStateToArtikCloud(result[0],result[2],result[1]);//parking,temperature,waterlevel
sendDataToArtikCloud(data);
});
});
process.on('SIGINT', exitClosePins);
I am getting an error on my raspberry pi
enter image description here
Suggest me a solution.
The documentation will tell you that Readline is spelled with a capital R
https://www.npmjs.com/package/serialport#module_serialport--SerialPort.parsers
parser: serialport.parsers.Readline("\n")
~
[TypeError: serialport.parsers.readline is not a function.]
If it has not been resolved yet, try this method.
var serialport = require("serialport")
var SerialPort = serialport.SerialPort;
var sp = new serialport("/dev/ttyACM0"),{
BaudRate: 9600,
parser: new serialport.parsers.Readline("\r\n")
});
I hope your problem is solved.

Beaglebone Black revC

I am connecting BBB and a set of arduinos over the serial port (ttyO2).
I have an array to be sent from BBB to a set of arduinos.
I need to make the BBB sends a request and wait for a reply from one of the arduinos, but if no arduino replies within an interval, the BBB must send the following value in the array.
I have the connection and arduinos ready for their jobs.
The problem is that the BBB will listen on the port and complete the execution of the code at the same time. I need to make it listen for a specific time, if data received=> process it; else complete the following part of code (send the remaining part of the array). This job need to be in a loop.
I have been trying to use setTimeout, recursion, but with no success!
I am using the following code to listen and write on ttyO2:
` var b = require('bonescript');
//opening the serial port
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200
});
var i = 0;
serialPort.on("open", function () {
console.log('opened');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
serialPort.write( i + "\n", function(){});
});
});
serialPort.on("data", function (data) {
console.log("here: "+data);
});
`
var b = require('bonescript');
//opening the serial port
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200
});
var i = 0;
var waiting_interval = 5000;
var slaves = ["S1", "S2" , "S3", "S4", "S5"];
serialPort.on('open',function my(){
console.log("opened");
serialPort.on('data', function listenToSlaves(data){
console.log("returned: " + data);
});
writeToSlaves();
});
function writeToSlaves(){
// setInterval(serialPort.write(slaves[i], function(){ console.log("I
wrote to slave: " + i)}), 5000);
serialPort.write(slaves[i], function(){ });
console.log("I wrote to slave: " + i);
if(i<slaves.length - 1) i++;
else i=0;
setTimeout(writeToSlaves, waiting_interval);
}

Node.js Processes Don't Detect Port is Already Being Used

I am trying to have two different Node processes (using Cluster) try to become servers to a Port. However, whenever the second process gets to the port, it doesn't detect that the port is being used.
I suspect the reason why they are not detecting if the port is open or not is due to the nature of callbacks (I'm detecting if the port is used or not using the portInUse function, so it is fetched asynchronously, and might cause some type of conflict later on).
Here is the code:
var cluster = require('cluster');
var net = require('net');
var PORT = 1337;
var list = {};
var portIsBeingUsed = false;
// Variable that detects if the port is in use.
var portInUse = function(port, callback) {
var server = net.createServer(function(socket) {
socket.write('Echo server\r\n');
socket.pipe(socket);
});
server.listen(port, 'localhost');
server.on('error', function (e) {
callback(true);
});
server.on('listening', function (e) {
server.close();
callback(false);
});
};
if (cluster.isMaster) {
for (var i = 0; i < 2; i++) {
cluster.fork();
}
Object.keys(cluster.workers).forEach(function(id) {
console.log("I am running with ID : "+ cluster.workers[id].process.pid);
list[cluster.workers[id].process.pid] = 0;
});
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else { // Rest of the logic with all Processes goes here.
// Get the Process ID of the current process in execution.
var pid = cluster.worker.process.pid;
console.log("This is process " + pid + " working now.\n");
// Verify if Port is being used.
portInUse(PORT, function(returnValue) {
if(returnValue) { // Become a Client to the Server
console.log("port " + PORT + " is being used.\n\n");
becomeClient(pid);
} else { // Become a Server
console.log("port" + PORT + " is not being used.\n\n");
becomeServer(pid);
}
});
}
function becomeServer(pid) {
var server = list[pid];
server = net.createServer(function (socket) {
socket.write('Hello Server 1\r\n');
socket.end("hello");
console.log("Someone connected to Server 1. \n");
socket.pipe(socket);
});
server.listen(PORT, function(){
console.log("Process " + pid + " has become the Server on Port " + PORT);
});
server.on("error", function() {
console.log("there was an error on Process " + pid);
console.log("this error was becoming a Server.");
});
}
function becomeClient(pid) {
var client = list[pid];
client = net.connect({port: PORT}, function() {
list[pid].write("I am connected to the port and my pid is " + pid);
});
client.on('data', function(data) {
console.log(data.toString());
list[pid].end();
});
client.on('end', function() {
console.log('disconnected from server');
});
}
And here is the output:
So the first process (In this case Process 9120) becomes the server on port 1337, but then the second process doesn't detect that the port is being used and somehow becomes the server as well (I would expect an EADDRINUSE here, not sure why it isn't showing any errors).
Any help or clarification as to why this isn't working would be greatly appreciated.
Thanks,
This is expected behavior and it is how the cluster module works (by default). It's what allows incoming requests to the same port to be easily distributed among the available workers.
A large part of the point of cluster involves port sharing, so that you can have multiple workers take turns serving requests. The worker processes just request a port from the master, which actually opens the port, and then the master hands requests back to any workers that have requested that port.

How to send JSON data from client to node.js server.

Here is server.js
var express = require("express"),
http = require("http"),
mongoose = require( "mongoose" ),
app = express();
app.use(express.static(__dirname + "/client"));
app.use(express.urlencoded());
mongoose.connect('mongodb://localhost/PvdEnroll', function(err) {
if (err) {
console.log(err);
} else {
console.log('Connected to mongodb!');
}
});
var CheckBoxSchema = mongoose.Schema({
npi: String,
boxes:[ String]
});
var CheckBox = mongoose.model("CheckBox", CheckBoxSchema);
http.createServer(app).listen(3000);
// here's where we get something from the client.
app.get("/checkbox.json", function (req, res) {
CheckBox.find( {}, function(err, CheckBox) {
console.log("STUBB2", checkbox);
res.json(checkbox);
});
});
app.post("/checkbox", function (req, res)
console.log("POSTING TO DB: ",req.body);
var newCkBoxData = new npiChecks({"npi": req.body.npi, "boxes":req.boxes});
newCkBOxData.save(function(err, results) {
if (err !== null) {
console.log(err);
res.send("ERROR");
} else {
CheckBox.find({}, function(err, result) {
if (err !== null) {
// the element dir not get saved
res.send("ERROR");
}
res.json(result);
});
}
});
});
The client, secA.js, pertains to a single HTML page.
var main = function (checkBoxObjects) {
"use strict";
$.getJSON("../data/checkBoxesA.json", function(checkBoxTxt) {
checkBoxTxt.forEach(function (data) {
$(".checkbox-input").append("<input type='checkbox' unchecked/>");
$(".checkbox-input").append(' ' + data.label + "<br/>");
$(".checkbox-input").append(' ' + data.note + "<br/>");
$(".checkbox-input").append(' '+ "<br/>");
});
});
};
$(document).ready(main);
providerNPI_ckBs = [];
NPI_number = [];
var loopForm = function(form) {
for ( var i = 0; i < form.elements.length; i++) {
if (form.elements[i].type == 'checkbox')
if (form.elements[i].checked == true) {
providerNPI_ckBs += 1 + ' ';
} else {
providerNPI_ckBs += 0 + ' ';
}
}
if (providerNPI_ckBs.length > 0)
if (NPI_number.length > 0)
createJSONobj();
}
var getNPI = function() {
NPI_number = document.getElementById("text_field1").value;
if (NPI_number.length > 0)
if (providerNPI_ckBs.length > 0) {
createJSONobj();
}
}
var createJSONobj = function() {
var JSONobj = '{' + JSON.stringify(NPI_number) + ':' +
JSON.stringify(providerNPI_ckBs) + '}';
JSON.stringify(JSONobj);
console.log(JSONobj);
// here we'll do a quick post to our todos route
$.post("npi_checks", JSONobj, function (response) {
console.log("We posted and the server responded!");
console.log(response);
});
}
// Note: This is temporary as I'm only intending to sent JSON data one way
// to the server. I'd just like to verify that I can send data both ways
$(document).ready(function (checkBoxObjects) {
$.getJSON("checkbox.json", function (checkBoxObjects) {
console.log("Client Recieved Array from Server: ", checkBoxObjects);
main(checkBoxObjects);
});
});
The Chrome console responds immediately with GET http://127.0.0.1:3000/html/checkbox.json 404 (Not Found)
The page loads and will accept data which the secA.js script formats as JSON. The database has been started by the server. All I need to know is how to send the data over to the server!
I'm clearly new to javascript and producing this application is part of learning the language along with MongoDB. I've structured this application similarly to an example tutorial book. One difference is that in the tutorial the traffic is two ways between client and server.
Any help is appreciated!
If the first argument to post, on the client side, is changed from ""npi_checks" to "/checkbox" to match the first argument app.post the data gets to the server and is loaded into mongoldb. This is the simple solution.

Categories

Resources