I am a trying to make a small web server for testing. I made it with NodeJS. But something unexpected happened. The webpage passed by the NodeJS server couldn't be displayed properly. But the webpage worked perfectly when I used php+Apache. When I opened the source code received at my client side, there are no observable difference. Here is my code:
Server.js
var http = require('http');
var fs = require('fs');
var url = require('url');
var Max = 30;
var port = process.argv[2];
var server = http.createServer( function (request, response) {
var pathname = url.parse(request.url).pathname; if (pathname == "") pathname = "index.html";
console.log("Request for " + pathname + " received.");
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data.toString());
}
response.end();
});
}).listen(port);
console.log('Server running at http://127.0.0.1:8081/');
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
socket.on('close', function () {
console.log('socket', socketId, 'closed');
delete sockets[socketId];
});
socket.setTimeout(4000);
});
function anyOpen(array) {
for (var ele in array) {
if (ele) return true;
}
return false;
}
(function countDown (counter) {
console.log(counter);
if (anyOpen(sockets)) {
return setTimeout(countDown, 1000, Max);
} else if (counter > 0 ) {
return setTimeout(countDown, 1000, counter - 1);
};
server.close(function () { console.log('Server closed!'); });
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
})(Max);
Chatroom2-0.php
<!DOCTYPE html>
<html>
<head>
<style>
textarea {
width:95%;
rows:50;
height:80%;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script type="text/javascript">
var str = "";
function enter(e){
if (e.keyCode == 13 && document.getElementById("Input").value) {
//alert("Enter!!!!");
sendInput();
document.getElementById("Input").value = "";
}
};
function updateBoard() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("MsgBoard").innerHTML = xmlhttp.responseText;
}
var textarea = document.getElementById('Output');
textarea.scrollTop = textarea.scrollHeight;
};
xmlhttp.open("POST","Server.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Username&Content="+document.getElementById("Username").value);
};
function sendInput() {
username = document.getElementById("Username").value; if (!username) username = "Gotemptyname";
msg = document.getElementById("Input").value; if (!msg) msg = "GotNothing";
if (msg) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","Server.php",true);
//xmlhttp.open("POST","test.txt",true);
//xmlhttp.send();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("Type=Message&Username="+username+"&Content="+msg);
//alert(xmlhttp.responseText);
}
};
</script>
</head>
<body onload="setInterval('updateBoard()',1000)">
<div id="MsgBoard"></div>
<form name="UsrInput">
<?php
if (isset($_POST["Username"]))
echo '<input type="text" id ="Username" value="'.$_POST["Username"].'" disable>';
else {
header("Location: /login/index.html");
die();
}
?>
<input type="text" id="Input" onkeypress="enter(event)" value="" >
</form>
</body>
</html>
Users should be able to access the Chatroom2-0.php after login. The login functionality is also ok. But when I entered the Chatroom2-0.php, I got a String, next to my textbox.
'; else { header("Location: /login/index.html"); die(); } ?>
I noticed that the string is part of my php code in the file. I don't know what's happening. I think this might have something to do with the response.write() or the data.toString() function. Maybe the function changed something in my coding? How could I solve this problem.
Anyway, I appreciate for any help given.
The problem is that you are trying to run php code on a nodejs server. There is no solution to this, as node is not a php interpreter, so it sees everything as html text; thus your php code appearing on the page. You need to create an entirely different html for the node project.
Related
<button type="submit" class="btn btn-success" onclick="on()">Force ON </button>
<script type="text/javascript">
function on(){req.url="/ledOn";}
</script>
This is my HTML button and i just need to route make it route to "ledOn" page in server.js file in order to perform some operations.
and this is the server.js file code.
var http = require('http');
var ejs = require('ejs');
var fs = require('fs');
var system = require('child_process').exec;
//var mraa = require('mraa');
var ledstatus = "off";
//var pin_2 = new mraa.Gpio(2);
//pin_2.dir(mraa.DIR_OUT);
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html', 'utf-8', function(err, content) {
if (err) {
res.end('error occurred');
return;
}
var temp = 'some temp';
console.log("Request: " + req.url);
if(req.url === "/ledOn") {
//pin.write(0);
ledstatus = "on";
console.log("pin 7 on");
}
if(req.url === "/ledOff") {
//pin.write(1);
ledstatus = "off";
console.log("pin 7 off");
}
var renderedHtml = ejs.render(content, {temp: temp, ledstatus:ledstatus});
res.end(renderedHtml);
});
}).listen(8080);
** i wanna add more buttons with more routes to my html page to use it controlling my galileo board, so any help would be appreciated **
I have this code.I send messages to server but i don't receive them.I have code from a post where the user say is working.I have a xmpp server where i can connect with strophe.
<html>
<head>
<script type="text/javascript" src="angular/angular.min.js"></script>
<script type="text/javascript" src="strophe.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="init">
</div>
<script type="text/javascript">
BOSH_SERVICE = 'http://localhost:5280/http-bind/';
xmpp_user = "user";
xmpp_domain = "localhost";
xmpp_userdomain = "user#localhost";
xmpp_password = "secret";
angular.
module('myApp', []).
controller('init', function(xmppAuth){
xmppAuth.auth(xmpp_userdomain,xmpp_password);
on_presence = function (presence){
console.log('presence');
return true;
}
on_message = function (message){
//console.log('message');
console.log(message);
return true;
}
}).
service('xmppAuth', function() {
return {
auth: function(login, password) {
connect = new Strophe.Connection(BOSH_SERVICE);
connect.connect(login, password, function (status) {
if (status === Strophe.Status.CONNECTED) {
console.log("Autentificare reusita!");
//try send helo
var message = "helo";
var to = "marian#localhost";
if(message && to){
var reply = $msg({
to: to,
type: 'chat'
})
.cnode(Strophe.xmlElement('body', message)).up()
.c('active', {xmlns: "http://jabber.org/protocol/chatstates"});
connect.send(reply);
console.log('I sent ' + to + ': ' + message);
}
//addhandler receive messg
connect.addHandler(onMessage, null, "message", null, null, null);
var onMessage = function (message){
console.log('S-a primit un mesaj');
console.log('message');
return true;
}
}
})
}
}
})
</script>
</body>
</html>
What i should do?Thanks for any help!
I had a similar problem and I noticed that setting the handler before sending any message would allow you to read the messages, even those you send.
Below is a working code which I have tested
...
server_connection.connect(user_id, password, function(status){
if (status == Strophe.Status.CONNECTED){
on_connected();
}
});
function on_connected(){ server_connection.addHandler(on_message, null, 'message');}
var on_message = function(message){ /* work with message here */ }
You won't receive messages which you send, only incoming messages, or use MUC plugin for history.
I am trying to create realtime chat in my SPA app. I got the chat working , but when I move to another page and head back to the chat page , it starts loading messages twice. Here is my server side for socket.io:
var io = require('socket.io').listen(app.listen(config.port));
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'You are chatting now !' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
I tried using io.sockets.once instead of io.sockets.on but it doesn't show chat 2nd time ..
And here is my client side together with html (jade template engine):
#content(style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;')
input#field(style='width:350px;')
input#send(type='button', value='send')
script(src='/socket.io/socket.io.js')
script.
$("#field").keyup(function(e) {
if(e.keyCode == 13) {
sendMessage();
}
});
var messages = [];
var socket = io.connect('localhost:3030/#/chat');
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
socket.on('message', function (data) {
if(data.message) {
messages.push(data.message);
var html = '';
for(var i=0; i<messages.length; i++) {
html += messages[i] + '<br />';
}
content.innerHTML = html;
content.scrollTop = content.scrollHeight;
} else {
console.log("There is a problem:", data);
}
});
sendButton.onclick = sendMessage = function() {
var text = field.value;
socket.emit('send', { message: text });
field.value = '';
};
I want to fix this , so when I go back 2nd time it doesnt show 2 times , or for 3rd time to show it 3 times and so on ... Help is greatly appreciated :)
If I understand correctly, you want correct persistence between page refreshes, just add an array on the server to collect the messages and tell new connections all about them.
I really just use the docs to accomplish my goals (link for reference http://socket.io/docs/server-api/)
for the code below to run, it is necessary to do these commands in the working directory
npm install express
npm install socket.io
(server code)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
//serve up the file, the code for this is below, I translated your jade to html
app.get('/', function(req, res){
res.sendfile('index.html');
});
//note this will get big eventually with lots of users
var message_past = [];
io.on('connection', function(socket){
socket.emit('server-message', { message: 'Welcome !' });
// tell user recent posts
for (var i = 0; i < 20 && !!message_past[i] ; i ++) socket.emit('user-message',message_past[i]);
// save the message and update everyone with it
socket.on('user-message', function (data) {
message_past.push(data);
// io.emit will tell everyone <-- I think what you want
// socket.broadcast.emit will tell everyone but this socket
// socket.emit will tell just this socket
io.emit('user-message', data);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and the client code
<input id='field' type="text" style='width:350px;'/>
<input id='send' type='button' value='send'/>
<div id='content' style='width: 500px; height: 300px; margin: 0 0 20px 0; border: solid 1px #999; overflow-y: scroll;'>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src='/socket.io/socket.io.js' ></script>
<script type="text/javascript">
$("#field").keyup(function(e) {
if(e.keyCode == 13) {
sendMessage();
}
});
var socket = io.connect('localhost:3000/#/chat');
console.log(socket)
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
var display_message = function( data ) {
if(data.message) {
$(content).append(data.message+'<br/>');
content.scrollTop = content.scrollHeight;
} else {
console.log("There is a problem:", data);
}
};
socket.on('server-message', display_message);
socket.on('user-message', display_message);
sendButton.onclick = sendMessage = function() {
var text = field.value;
socket.emit('user-message', { message: text });
field.value = '';
};
</script>
I am trying to implement a simple "global" counter that updates based on every user that clicks the button on their browsers button. For example, if you go to the website and click the button, I will see the counter increase on my side if I'm on the same website. I sought to do this with long polling, but am facing some issues. Mainly the server variable is not coming back as I think it should.
The server:
package main
import (
"net/http"
"log"
"io"
"io/ioutil"
)
var messages chan string = make(chan string, 100)
var counter = 0
func PushHandler(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
w.WriteHeader(400)
}
counter += 1
messages <- string(counter)
}
func PollResponse(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, <-messages)
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/poll", PollResponse)
http.HandleFunc("/push", PushHandler)
err := http.ListenAndServe(":8005", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
The client:
<html>
<script language=javascript>
function longpoll(url, callback) {
var req = new XMLHttpRequest ();
req.open ('GET', url, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
callback(req.responseText);
longpoll(url, callback);
} else {
alert ("long-poll connection lost");
}
}
};
req.send(null);
}
function recv(msg) {
var box = document.getElementById("counter");
box.value += msg + "\n";
}
function send() {
var box = document.getElementById("counter");
var req = new XMLHttpRequest ();
req.open ('POST', "/push?rcpt=", true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if (req.status == 200) {
} else {
alert ("failed to send!");
}
}
};
req.send("hi")
//box.innerHTML += "test" ;
}
</script>
<body onload="longpoll('/poll', recv);">
<h1> Long-Poll Chat Demo </h1>
<p id="counter"></p>
<button onclick="send()" id="test">Test Button</button>
</body>
</html>
The counter variable is not coming back from the server for some reason. I believe I am changing the state every time the button is clicked and so the longpolling function should get the newly updated counter variable. If you have any suggestions, please let me know!
I see two issues in you program:
1. In the server:
messages <- string(counter)
You should use "strconv" package
messages <- strconv.Itoa(counter)
string(0) will return something like []byte{0} not a "0"
2. In your client:
function recv(msg) {
var box = document.getElementById("counter");
box.value += msg + "\n";
}
Should be:
function recv(msg) {
var box = document.getElementById("counter");
box.innerHTML += msg + "\n";
}
I don't think the p element have value property
First I built a websocket server using node js and ws module. Then using chrome and firefox, I connect to that server and the connection is successfully established. However, the message I send from browsers does not arrive at the server. I have some code on server to console.log out if message is received. Nothing appears, however when I refresh the browser, the messages I previously sent arrive. The messages did not arrive when sent them but only once I refresh the page. I don't know why. This seems to work in from some other computers but not mine.
Here is the server code:
var WebSocketServer = require('ws').Server
, http = require('http')
, express = require('express')
, app = express();
app.use(express.static(__dirname + '/views'));
var rmi = require('./RMIClient.js');
console.log(rmi);
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
// from here is the logic codes
var clients = [];
var clientId = 0;
wss.on('connection', function(ws) {
console.log("connection established for client "+ (clients.length+1));
clients.push(ws);
console.log("index is " + clients.indexOf(ws));
clientId += 1;
ws.send("Hello Client: " + clientId);
//
// ws.send("Welcome from AMTT Chatting Server");
ws.on('message',function(data){
console.log('message receieved : '+data);
for(var i = 0;i<clients.length;i++){
clients[i].send(data);
}
});
ws.on('a',function(){
console.log("a event fire from client");
});
ws.on('close', function() {
var index = clients.indexOf(ws);
console.log('stopping client interval '+index);
if (index > -1) {
clients.splice(index, 1);
}
});
});
Here is the client code:
<html>
<script>
//var ws = new WebSocket('ws://localhost:8080/');
var messagearea,inputarea,sendButton;
var connection = new WebSocket(/*'wss://echo.websocket.org');*/'ws://192.168.8.195:8080/');
// When the connection is open, send some data to the server
console.log(connection.readyState);
connection.onopen = function () {
console.log(connection.readyState);
inputarea.disabled = false;
sendButton.disabled = false;
};
// Log errors
connection.onerror = function (error) {
console.log('sorry connection fail:' + JSON.stringify(error));
};
// Log messages from the server
connection.onmessage = function (e) {
messagearea.value = messagearea.value + '\n' + e.data;
console.log('Server: ' + e.data);
};
function sendMessage(){
if(inputarea.value !='')
connection.send(inputarea.value);
inputarea.value = '';
}
</script>
<body>
<textarea rows="15" cols="100" id="messagearea" disabled>
</textarea>
<br/>
<textarea rows="2" cols="90" id="inputarea" required autofocus>
</textarea>
<input type = 'button' value = 'send' id = 'sendbutton' onclick = "sendMessage()"/>
</body>
<script>
messagearea = document.getElementById('messagearea');
messagearea.value = '';
inputarea = document.getElementById('inputarea');
inputarea.value = '';
inputarea.disabled = true;
sendButton = document.getElementById('sendbutton');
sendButton.disabled = true;
</script>
</html>
And again I found that kind of situation when I develop that code in java and deployed in wildfly server. I am lost. I think there is something concerned with my network card. Because that same code work perfectly in my friend's machine.
Does anybody experience this situation ? or any solution?
You can also try the following:
connection.addEventListener("message", function (e) {
processSocketMessage(e);
});
good luck :)