Scenario:
I have a server which is accessed by multiple users. Server for ex: http://127.0.0.1:8081
It has one button and by clicking on it, it runs one selenium automated test.
I want to get a list of tests currently running by multiple users.
So for ex: if 5 users are accessing that server and clicked on that button 2 times it means that automated tests running are 10.
How can I get above count in node.js express like how many processes are running?
My server.js :
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send(
'<form action="/server" method="POST">' +
' <input type="submit" name="server" value="Run Script" />' +
'</form>');
});
app.post('/server', function (req, res) {
var fork = require('child_process').fork;
var child = fork('./test');
res.send('Test Started....');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
Not tested, but the following should do something like what your after.
Not sure were you wanted to access counter, so done another route /counter that echo the current counter out.
var express = require('express');
var app = express();
var counter = 0;
app.get('/', function (req, res) {
res.send(
'<form action="/server" method="POST">' +
' <input type="submit" name="server" value="Run Script" />' +
'</form>');
});
app.get('/counter', function (req, res) {
res.end("Counter = " + counter);
});
app.post('/server', function (req, res) {
var fork = require('child_process').fork;
var child = fork('./test');
counter ++;
child.on("close", function () { counter --; });
res.send('Test Started....');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
You can maintain global count for clicked button.
global.total_tests = 0; // note this line
var express = require('express');
var app = express();
app.post('/server', function (req, res) {
var fork = require('child_process').fork;
var child = fork('./test');
res.send('Test Started....');
total_tests++; // note this line
});
I hope this help.
Thanks.
I'd recommend using ps-node as suggested in this earlier Stackoverflow post.
Related
I'm using node.js to read data from socket on my web application (server). I receive data and make some changes on webpage (ex: change the color of polyline) but when a client after that changes connects, cannot see the changed color unless a new data is sent to server! So how client can see the previous changes which were on server?
here is my code
app.js
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server); //pass a http.Server instance
server.listen(3000); //listen on port 80
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
//var app = require('http').createServer(handler);
//var io = require('socket.io').listen(app);
var fs = require('fs');
var mySocket = 0;
//app.listen(3000); //Which port are we going to listen to?
function handler (req, res) {
fs.readFile(__dirname + '/index.html', //Load and display outputs to the index.html file
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
});
//UDP server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
server.on("listening", function () {
var address = server.address(); //IPAddress of the server
console.log("UDP server listening to " + address.address + ":" + address.port);
});
server.bind(41181);
index.html
<html>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.1.14:3000');
socket.on('field', function (data) {
console.log(data);
$("#field").html(data);
switch(data)
{
case "1":
$("#path1").css("stroke", "red");
$("#progress1").css("backgroundColor", "red");
break;
}
});
</script>
<body>
<polyline id="path1" points="600,270 560,262 460,270 440,300" style="fill:none;stroke:green;stroke-width:3" />
</body>
</html>
On connection you have to emit already existing changes to socket client.
var myMessage;
io.sockets.on('connection', function (socket) {
console.log('Webpage connected'); //Confirmation that the socket has connection to the webpage
mySocket = socket;
mySocket.emit('field', "" + myMessage); // <<-- like this
server.on("message", function (msg, rinfo) {
console.log("Broadcasting Message: " + msg); //Display the message coming from the terminal to the command line for debugging
if (mySocket != 0) {
myMessage = msg;
mySocket.emit('field', "" + msg);
mySocket.broadcast.emit('field', "" + msg); //Display the message from the terminal to the webpage
}
});
});
Following part of my code is used for retrieving the data from TI sensor tag. So we are using sensortag node.js module to get the data and sending it to client using socket.io. on local host the application is working fine but , when i push the code to heroku cloud web sockets part is not working.
Error : the server responded with a status of 400 (Bad Request)
https://peaceful-plateau-6281.herokuapp.com/socket.io/?EIO=3&transport=polling&t=1449192192332-3 400 (Bad Request)
Following is my code :
var express = require('express');
var port = process.env.PORT || 3000;
var app = module.exports.app = express();
var server = require('http').Server(app);
//var io = require('socket.io')(server);
var SensorTag = require('sensortag');
var path = require('path');
var io = require('socket.io').listen(server.listen(port,function(){
console.log("We have started our server on port " + server.address().port);
// SensorTag.discover(function(tag) { and close it with }); above ondiscover mthod
function onDiscover(tag){
tag.on('disconnect', function() {
console.log('disconnected!');
process.exit(0);
});
function connectAndSetUpMe() { // attempt to connect to the tag
console.log('connectAndSetUp' + tag.id);
tag.connectAndSetUp(enableDataPoints); // when you connect, call enableIrTempMe
}
function enableDataPoints(){
console.log('enabling Temp datapoint');
tag.enableIrTemperature(notifyMe);
tag.enableHumidity(notifyHumd);
tag.enableBarometricPressure(notifyPress);
tag.enableAccelerometer(notifyAccel);
}
function notifyMe(){
console.log("notifying temp datapoints");
tag.notifyIrTemperature(listenForReading);
}
function notifyHumd(){
console.log("notifying humd datapoints");
tag.notifyHumidity(listenForHumdReading);
}
function notifyPress(){
console.log("notify pressure");
tag.notifyBarometricPressure(listenForPress);
}
function notifyAccel(){
console.log("notify Accerlerometer");
tag.notifyAccelerometer(listenForAcc);
}
function listenForReading(){
tag.on('irTemperatureChange', function(objectTemp, ambientTemp) {
console.log('\tObject Temp = %d deg. C', objectTemp.toFixed(1));
function TempChange() {
io.sockets.emit('objTemp', { sensorId:tag.id, objTemp: objectTemp, ambTemp: ambientTemp});
};
TempChange();
});
}
connectAndSetUpMe();
}
SensorTag.discover(onDiscover);
})
);
io.on('connection', function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
And at the client side
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
<script>
var socket = io.connect("\/\/"+window.location.hostname+":"+location.port);
//var socket = io.connect(window.location.hostname);
console.log("window.location.hostname"+location.port);
socket.on('objTemp', function(data) {
$('#objTemp').html(parseInt(data.objTemp));
console.log("This is my places");
$('#ambTemp').html(parseInt(data.ambTemp));
</script>
</head>
<body>
<p id="objTemp"></p>
</body>
</html>
I am not getting the data at the client side through websockets.Can anybody please help me out.
Thanks®ards,
Shivadeepthi
I had the same error and just fixed.
var io = require('socket.io').listen(server);
io.set('origins', '*:*');
io.set('match origin protocol', true);
I am trying to learn Node and build a simple chat application. It seems like everyone uses socket.io. I would like to understand how to do this on a more fundamental level using get and post.
Basically, all I want to do is have a form that takes an input and reposts it below the form for everyone to see.
This is what I have so far:
//Requirements
var express = require('express');
var app = express();
//GET
app.get('/', function (req, res) {
// res.send('Hello World!');
var response =
"<HEAD>"+
"<title>Chat</title>\n"+
"</HEAD>\n"+
"<BODY>\n"+
"<FORM action=\"/\" method=\"get\">\n" +
"<P>\n" +
"Enter a phrase: <INPUT type=\"text\" name=\"phrase\"><BR>\n" +
"<INPUT type=\"submit\" value=\"Send\">\n" +
"</P>\n" +
"</FORM>\n" +
"<P>phrase</P>\n"+
"</BODY>";
var phrase = req.query.phrase;
if(!phrase){
res.send(response);
}else{
res.send(response);
res.send(phrase);
}
});
//For testing
app.get('/test', function(req, res){
res.send('I am a robot');
console.log('told visiter I am a robot');
});
//Run the app
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
I've been trying a bunch of things, but I am pretty stumped.
Did you hear about messaging backend jxm.io?
It works with JXcore (open sourced fork of Node.JS). JXM itself is an open source project, which you can find on github: jxm.
It's really fast and efficient, you can check some tutorials. For example, below is minimal code, that you need to run on server-side:
var server = require('jxm');
server.setApplication("Hello World", "/helloworld", "STANDARD-KEY-CHANGE-THIS");
server.addJSMethod("serverMethod", function (env, params) {
server.sendCallBack(env, params + " World!");
});
server.start();
The client's part can be found here:
Browser Client (JavaScript)
JXM also supports Java clients (runs on android) and node clients.
I'm trying to communicate node.js and a HTML script with socket.io. I'm trying that when i choose some value with a radio button, socket.io sends this value to node.js and then, return to the console. My problem is that socket.io doesn't send anything. I know it doesn't enter the socket function because i write an alarm in html if it enters, and nothing.
Node.js code is this:
var express = require("express");
var http = require("http");
var socketIO = require("socket.io");
var app = express();
app.get("/", function(req, res){
res.sendfile("./toggle?.html");
});
var server = http.createServer(app);
var io = socketIO.listen(server, {log: false});
io.sockets.on("connection", function(socket){
socket.on("sendVar", function(value){
console.log(value)
});
});
server.listen(5000);
And the HTML script is this:
<html>
<input type="radio" name="group1" value=1> ON<br>
<input type="radio" name="group1" value=0 checked> OFF<br>
<INPUT TYPE="Button" VALUE="Proceed" onClick="showBoxes(this.form)">
<script>
var radios = document.getElementsByName('group1');
function showBoxes(frm){
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
var x=radios[i].value;
alert(radios[i].value)
//Send the value of the radio button
var socket = io.connect("http://localhost:5000"); //client connection
socket.on("connect", function(){
alert("connected!")
socket.emit("sendVar", x);
});
break;
}
}
}
</script>
</html>
Do you have a specific need to have this web socket open? currently what you have an AJAX call would be more suited. you can handle this with the normal request, response method using express.
You can use a simple express get handler:
app.get('/', function(req, res){
res.send('hello world');
});
or you can use the router:
var app = express();
app.route('/events')
.all(function(req, res, next) {
// runs for all HTTP verbs first
// think of it as route specific middleware!
})
.get(function(req, res, next) {
res.json(...);
})
.post(function(req, res, next) {
// maybe add a new event...
})
each solution would be more suited that a socket.
source: http://expressjs.com/api.html
I am new to this, I built a standard web chat application and I see the power of nodejs, express, socket.io.
What I am trying to do is trigger events from a phone to a website, like a remote control. There is server javascript that listens to events from the client, and client javascript that triggers those events, this is how I understand it correct me if I am wrong.
I learned in the chat app I can send an object from anywhere, as long as they are connected to my server through a specific port http://my-server-ip:3000/. Basically all events are inside the index page, and the connection is index to server to index.
What I am trying to learn is how to trigger events from an external page, I've seen things like http://my-server-ip:3000/ws or something like that, the idea is to connect to a mobile interface that isn't the actual index or website itself, but this interface communicates with the node server using it as a dispatcher to trigger events on the main index page.
Basically what I have learned was index to server to index. I am not sure how I can go custom-page to server to index.
I see that in my app.js, my understanding is that the socket listens to sends which is on the client then it emits the message.
io.sockets.on('connection', function (socket) {
socket.on('sends', function (data) {
io.sockets.emit('message', data);
});
});
I tried creating a test.html that has a button on it, I tried listening to it, here is a screen shot.
Here is my client code
window.onload = function() {
var messages = [];
var socket = io.connect('http://my-server-ip:3000/');
var socketTwo = io.connect('http://my-server-ip:3000/test.html');
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
var name = document.getElementById("name");
var trigBtn = document.getElementById("trigger-btn");
socket.on('message', function (data) {
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
//FROM DEMO
// sendButton.onclick = sendMessage = function() {
// if(name.value == "") {
// alert("Please type your name!");
// } else {
// var text = field.value;
// socket.emit('send', { message: text, username: name.value });
// field.value = "";
// }
// };
//I include this javascript with test.html and trigger
//this button trying to emit a message to socketTwo
trigBtn.onclick = sendMessage = function() {
socketTwo.emit('send', { message: 'String test here' })
}
}
I am sure that is all wrong, but hopefully this makes sense and someone can help me trigger events from another page triggering to the index.
Here is my app.js server code
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/test.html', function(req, res) {
res.send('Hello from route handler');
});
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
All code posted above is just testing cookie cutter code, I am learning from scratch so the above can be totally changed, it's just there as a starter point.
This is so cool I got it to work, so my logic was correct. There were just a few things I was missing. Here it is.
I am not going to post all the server side javascript code, but here is the main logic after listening to the port etc.
// Set a route and in a very dirty fashion I included a script specific
// for this route, earlier I was using one script for both route.
// I also forgot to include the socket.io hence the error in the image above.
app.get('/test', function(req, res) {
res.send('<script src="/socket.io/socket.io.js"></script><script type="text/javascript" src="javascripts/trigger.js"></script><button id="test" class="trigger-btn">Trigger</button>');
});
// This listens to `send` which is defined in the `test` route
// Upon this action the server emits the message which
// is defined inside the index main route I want stuff displayed
io.sockets.on('connection', function (socket) {
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
Here is what the index client,js script looks like
window.onload = function() {
var messages = [];
var socket = io.connect('http://my-server-ip:3000');
var content = document.getElementById("content");
socket.on('message', function (data) {
if(data.message) {
messages.push(data);
var html = '';
for(var i=0; i<messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
}