Here I have a code for sum 3 numbers i+j+k but I waht to know how to configure server file to work with setTimeout function... is there some restriction?
so, here is mycode:
index.jade
!!! 5
html
head
title Test
body
form(name='form1', method='post', action='')
label(for='1')
input#1(type='text', name='1')
label(for='2')
input#2(type='text', name='2')
label(for='3')
input#3(type='text', name='3')
input(name='submit', type='button', value='submit')
span #{result}
app.js
var express = require('express');
app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false });
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.use(express.bodyParser());
app.get('/', function(req, res){
var result;
res.render('index', {result: ''});
});
app.post('/', function(req, res){
var i = req.param('1', 0);
i = parseInt(i);
var j = req.param('2', 0);
j = parseInt(j);
var k = req.param('3', 0);
k = parseInt(k);
var r = i+j+k;
res.render('index', {result:r});
});
app.listen(3010);
How etc. to block user action (click,doubleclick,rightclick) and show him a div with text "You can do any action" in first 5 seconds and after that user can do action but after 60 seconds again can't do any action... Can I do this with setTimout function or HOW???
sorry for my english
You cannot do this on the server side. You have to insert a client side javascript that blocks the interaction and unblocks it again after 5 sec.
The code for doing this on the client side would be something like this:
// this code should be executed when the client receives a message from the server.
var overlay = document.getElementById("your-element-id");
overlay.style.visibility = "visible";
window.setTimeout(function () {
overlay.style.visibility = "hidden";
}, 5000);
You should take the following steps to achieve what you want:
1. The user loads the page.
2. The user receives a message from the server, stating that he is being synchronized
3. Then either after a specified time or after another message from the server you unblock the user
4. Finally you start the game
Related
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.
});
});
});
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
Going nuts trying to get past this. Should be trivial, but I'm obviously doing something stupid. Goal is to upload a file inside Express. In short request.files is coming back as undefined in my route handler :
//modules ==========================================
// ExpressJS 4.0 used for the middleware and web framework
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var jsxml = require("node-jsxml");
var XMLWriter = require('xml-writer');
var request = require("request");
var fs = require('fs');
var app = express();
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
// Did I screw this up??!
app.use(bodyParser({keepExtensions:true,uploadDir: __dirname + '/public/uploads'}));
app.engine('html', require('ejs').renderFile);
app.use(cookieParser('Ronaldinho'));
app.use(session());
app.use(flash());
My file system:
Here's the form where a file is submitted (via a plugin called DropZone):
<div id="dropzone">
<form action="/uploads" name="upload" class="dropzone" id="demo-upload" enctype="multipart/form-data" method="post">
<input type="file" name="theFile" />
</form>
</div>
and the handler for the route:
app.post('/uploads', function (request, response) {
console.log('arrived');
console.log('1st TEST: ' + (request.files));
console.log('2nd TEST: ' + request.files.theFile.name);
fs.readFile(request.files.theFile.path, function (err, data) {
var newPath = "/home/path/to/your/directory/"+request.files.theFile.name;
console.log (newPath);
fs.writeFile(newPath, data, function (err) {
res.send("hi");
});
});
});
I hit the function above every time I upload a file, but find that request.files is undefined. Here's the result on the console (I'm using Brackets - interesting to me that I never even see the second test hit the console window...):
Any ideas what I'm screwing up?
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);
}
});
}