Simple Node.js chat program NOT using socket.io - javascript

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.

Related

How can I get running processes count in node.js

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.

How to start different actions on server with two buttons on website?

Please think about: I'm a beginner and try to learn progamming with javascript.
My goal: I have two buttons on a website. Each of both has to start his own function on the server.
Thanks to various tutorials I manage to trigger an action on the server. But now I have to distinguish two buttons for different server actions.
server.js
var express = require('express');
var app = express();
app.set('view engine', 'jade');
app.use(express.bodyParser());
var tweetText = 'A lot of tweet text...';
var user = 'Lutz';
var account = '#name';
var relevance = 0;
var tweetID_str = 0;
var RTs = 0;
//Send data from client/browser to server
app.post('/', function (req, res) {
console.log('works');
console.log(req.body);
});
//Send data from server to client
app.get('/', function(req, res){
relevance = relevance + 1;
tweetID_str = tweetID_str + 2;
RTs = RTs +3;
console.log('relevance: '+relevance+' userbytwo: '+tweetID_str);
res.render('index', { tweetText: 'Text: '+tweetText, account: '#User: '+account, user: 'User: '+user, relevance: 'RT per follower: '+relevance, tweetID_str: 'ID_str: '+tweetID_str, RTs: 'RTs: '+RTs });
/* updated this line */
});
app.listen(3000);
index.jade
doctype html
html(lang="de")
head
body
div
div!= tweetText
div!= account
div
div!= user
div!= relevance
div!= tweetID_str
div!= RTs
form(method='post')
div
input(type='submit', id='good', value='good')
input(type='submit', id='bad', value='bad')
<!-- input(type='text', name='username') -->
I guess, I have to parse the website action. Depending on the result the server starts his action. I'm right or wrong? And what do I have to do, that my code works?
You could probably capture the id of the button after click and then call the necessary action based on the id received using jquery. For example you could do something like:
$('#good').click(function(){
// Do the action on server that you want to do on click of good button.
});
$('#bad').click(function(){
// Do the action on server that you want to do on click of bad button.
});
Not sure if this is what you wanted ? Let me know your exact needs for more help.
You can use JQuery AJAX call to invoke a method as below.
$(document).ready(function() {
$('#good').click(function(){
$.ajax({
url: "/home"
}).then(function(data) {
alert(data); // Do whatever you want to do with response.
});
});
});

How can I send object by Node.js to browser in Real Time

I am working on a project in Node.js and Asterisk AMI
Asterisk sends events to Node.js server and Node.js sends events in Obj to browser
My problem is the node server does not send a new object when updating data from AMI
var AsteriskAmi = require('asterisk-ami');
var ami = new AsteriskAmi( { host: '127.0.0.1', username: 'admin', password: '123456' } );
var Send;
ami.on('ami_data', function(data){
// this obj update when ami send event
Send = data;
});
ami.connect(function(){
});
var http = require('http');
var app = http.createServer(function(req,res) {
res.setHeader('Content-Type': 'text/plain');
//my problem here , object was sent but not update when ami send other object
res.end(Send);
});
app.listen(3000);
1. res.end(Send)
This is your first issue. When somebody is visiting your host, you are sending hat was collected as last message and you are sending it to browser. And closing connection. For real time event transportation to browser you should use socket based mechanisms like socket.io.
To connect to this server you will have to use an html page.
Full working version in my environment - using asterisk-manager
In public_html/test/index.html:
<html>
<body>
<pre id="console">
</pre>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script>
var __url = 'http://localhost';
var __port = 3001;
__socketurl = __url + ':' + __port;
socket = io.connect(__socketurl);
socket.on('notification', function (data) {
document.getElementById('console').innerHTML = JSON.stringify(data) + "\r\n";
});
socket.on('ami_event', function (data) {
document.getElementById('console').innerHTML += JSON.stringify(data) + "\r\n";
});
</script>
</body>
</html>
Above code tries to connect to server at localhost:3001 and prints out every event coming from node app.
In public_html/test/node/app.js:
var app = require('http').createServer().listen(3001);
var io = require('socket.io').listen(app);
var AsteriskAmi = require('asterisk-manager');
var ami = new require('asterisk-manager')('25038','192.168.0.2','amilogin','amipassword', true);
io.sockets.on('connection', function(socket) {
socket.emit('notification', {message: "connected"});
});
ami.on('managerevent', function(data) {
console.log(data);
io.sockets.emit('ami_event', data);
});
ami.connect(function(){
});
Above code opens a socket at port 3001 and keeps it until user diconnects. Please refer to manual how to create IO servers here. Demo tutorias are available there also. Script does also connect to AMI itself and passes every event from AMI to every socket connected via socket.io.
Packages in public_html/test/node/packages.json:
{
"name": "Server",
"version": "0.0.1",
"private": true,
"dependencies": {
"socket.io": "latest",
"asterisk-manager": "latest"
}
}
Filled proper data in app.js to log into AMI, npm install'ed, node app.js and got it working flawlessly.

Nodejs and webSockets, triggering events?

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);
}
});
}

When namespacing I receive a "cannot GET error" displayed in browser

I'm using namespaces to differentiate between version of my socket.io chat app, and I'm having trouble with a "cannot GET error displayed in browser."
I plan on continually updating a chat app I made in a basic socket.io tutorial, and I want to be able to launch any version of it at any time. I'm going to do this by the use of namespaces. When I launch my app in browser at the location myserverlocation/v0.0.1 to access version 0.0.1 of my app, I get an error that states cannot GET '/v0.0.1'.
This is my server code:
var app = require('express')(),
server = require('http').Server(app),
io = require('socket.io').listen(server),
chat = io.of('/v0.0.1');
server.listen(80);
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// usernames which are currently connected to the chat
var usernames = {};
chat.on('connection', function (socket) {
// when the client emits 'sendchat', this listens and executes
socket.on('sendchat', function (data) {
// we tell the client to execute 'updatechat' with 2 parameters
io.sockets.emit('updatechat', socket.username, data);
});
// when the client emits 'adduser', this listens and executes
socket.on('adduser', function(username) {
// we store the username in the socket session for this client
socket.username = username;
// add the client's username to the global list
usernames[username] = username;
// echo to client they've connected
socket.emit('updatechat', 'SERVER', 'you have connected');
// echo globally (all clients) that a person has connected
socket.broadcast.emit('updatechat', 'SERVER', username + ' has connected');
// update the list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
});
// when the user disconnects.. perform this
socket.on('disconnect', function() {
// remove the username from global usernames list
delete usernames[socket.username];
// update list of users in chat, client-side
io.sockets.emit('updateusers', usernames);
// echo globally that this client has left
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
});
});
And this is my client code:
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('myserverlocation');
var chat = socket.of('/v0.0.1');
// on connection to server, ask for user's name with an anonymous callback
chat.on('connect', function(){
// call the server-side function 'adduser' and send one parameter (value of prompt)
chat.emit('adduser', prompt("What's your name?"));
});
// listener, whenever the server emits 'updatechat', this updates the chat body
chat.on('updatechat', function(username, data) {
$('#conversation').append('<b>' + username + ':</b> ' + data + '<br>');
});
// listener, whenever the server emits 'updateusers', this updates the username list
chat.on('updateusers', function(data) {
$('#users').empty();
$.each(data, function(key, value) {
$('#users').append('<div>' + key + '</div>');
});
});
// on load of page
$(function(){
// when the client clicks SEND
$('#datasend').click( function() {
var message = $('#data').val();
$('#data').val('');
// tell server to execute 'sendchat' and send along one parameter
chat.emit('sendchat', message);
});
// when the client hits ENTER on their keyboard
$('#data').keypress(function(e) {
if(e.which == 13) {
$(this).blur();
$('#datasend').focus().click();
}
});
});
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
<b>USERS</b>
<div id="users"></div>
</div>
<div style="float:left;width:300px;height:250px;overflow:scroll-y;padding:10px;">
<div id="conversation"></div>
<input id="data" style="width:200px;" />
<input type="button" id="datasend" value="send" />
</div>
My chat app works fine without the use of namespaces, at myserverlocation/. I cannot figure out why I keep getting this error. After some investigation I think my usage of io.of() is incorrect, but I cannot seem to fix the problem. I'm not sure if my problem lies in the server code, the client code, or both.
Edit: After more investigation, I think my problem lies in the follow segment of code (though I could be mistaken):
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
Edit2: The problem did in fact lie in the code segment above. I should have been sending my whole /Chat directory as static content instead of using res.sendfile() to send one file. I will formally answer my own question when stackoverflow lets me (I have to wait 8 hours to answer my own question).
I managed to find what my problem was. The problem lied in the following section of code:
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
I was sending one particular file upon connection to my server, when I should be sending my entire /Chat directory as static content. This way, I can chose what version of my chat app I would like to launch. I managed to do this by changing a few lines of code in my server code:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(80);
// Chat directory
app.use(express.static('/home/david/Chat'));

Categories

Resources