I have 3 iframes with reaveal.js presentations. And while they are not on node.js server they.re working perfectly. But I need socket.io to auto-refresh selected iframe when conents of file with reveal.js presentation is changed (I'm uploading a file using php manipulate it and making new .html file with presentation then I'm overwriting the old file).
Node.js server with chokidar is watching for change of file. And it's working.
But everything if failing when I'm joining socket.io and reveal.js together.
Site is constntly refreshing (don't know why i exluded emits) and because of that browser is crashing.
Server code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
var chokidar = require('chokidar');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
// io.on('connection', function (socket) {
// socket.emit('news', { hello: 'world' });
// socket.on('my other event', function (data) {
// console.log(data);
// });
// });
var watcher = chokidar.watch('file, dir, or glob', {
ignored: /[\/\\]\./, persistent: true
});
watcher.add('prez/prez1.html');
watcher.add('prez/prez2.html');
watcher.add('prez/prez3.html');
var log = console.log.bind(console);
watcher
.on('change', function(path) { log('File', path, 'changed');
//io.emit('restart1');
})
Client code:
<html>
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
// socket.on('news', function (data) {
// console.log(data);
// socket.emit('my other event', { my: 'data' });
// });
// socket.on('restart1', function (data) {
// var iframe = document.getElementById('ramka1');
// iframe.src = iframe.src;
// });
// socket.on('restart2', function (data) {
// var iframe = document.getElementById('ramka2');
// iframe.src = iframe.src;
// });
// socket.on('restart3', function (data) {
// var iframe = document.getElementById('ramka3');
// iframe.src = iframe.src;
// });
</script>
<iframe id="ramka1" width="100%" height="33%" src="prez/prez1.html"></iframe><br>
<iframe id="ramka2" width="100%" height="33%" src="prez/prez2.html"></iframe><br>
<iframe id="ramka3" width="100%" height="33%" src="prez/prez3.html"></iframe><br>
<style type="text/css">
iframe {
border:none;
}
</style>
</body>
</html>
Example presentation code:
<html>
<head>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/white.css">
</head>
<body>
<div class="reveal">
<div class="slides">
<section>Slide 1</section>
<section>Slide 2</section>
</div>
</div>
<script src="js/reveal.js"></script>
<script>
Reveal.initialize({controls: false, loop: true, autoSlide: 1000});
</script>
</body>
</html>
Related
I am working on a node.js app where I am using socket.io to send data to multiple clients but the socket is only able to send data to one client i.e if I open my webpage in two tabs its not working in both the tabs but when I open just 1 tab of webpage it is able to transmit the data.I dont know why? Can someone help,Here's my code:
server.js
var http = require("http"),
io = require("socket.io"),
fs = require("fs"),
util = require("util");
var backlog_size = 2000;
var filename = process.argv[2];
if (!filename) return util.puts("Usage: node <server.js> <filename>");
var linesCount = 0;
// -- Node.js HTTP Server ----------------------------------------------------------
server = http.createServer(function (req, res) {
console.log(req.url)
filePath = req.url
if(filePath=="/"){
filePath='./index.html'
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}
else
{
if(filePath=="/client"){
filePath = './client.html';
fs.readFile(filePath, function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading ' + filePath);
}
res.writeHead(200);
res.end(data);
});
}}
});
server.listen(8000, "0.0.0.0");
var fsTimeout
var textToSend=""
// -- Setup Socket.IO ---------------------------------------------------------
var socket = io(server, {
cors: {
origin: "*",
},
});
socket.on("connection", function (client) {
fs.watchFile(filename, function (curr, prev) {
console.log("file changed");
if (prev.size > curr.size) return { clear: true };
if(!fsTimeout){
if(prev.ctime.getTime() != curr.ctime.getTime())
{
console.log("file changed")
var stream = fs.createReadStream(filename, {
start: prev.size,
end: curr.size,
});
stream.on("data", function (lines) {
console.log(lines.toString());
textToSend+=lines.toString();
textlen=textToSend.split("\n").length;
// count=lines.toString().split("\n").length
// linesCount += count;
// console.log(linesCount);
console.log(textlen)
if(textlen<10)
{
console.log("me")
client.emit("tail", { lines: lines.toString("utf-8").split("\n") });}
else
{
console.log("client")
client.emit("room", { lines: textToSend.toString("utf-8").split("\n") }); };
});
}
fsTimeout = setTimeout(function() { fsTimeout=null }, 5000)}
}
);
});
In the above code I have added 2 clients,1 page is index.html and other is client.html and both are opening in the browser and getting connected to the socket but the data is not transmitting to any of them.Here's are my client codes:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Websockets tail Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="info" class="trebuchet"></div>
<div id="tail" class="monospace selection"></div>
<script type="text/javascript">
(function() {
var lines = 0, notice = $("#info"), buffer = $('#tail');
var socket = io.connect('http://127.0.0.1:8000/');
socket.on('connect', function() {
console.log('Connected to stream');
});
socket.on('room', function(msg) {
console.log("Message:");
console.dir(msg);
buffer.append(msg.lines.join('<br/>'));
buffer.scrollTop(lines*100);
lines = lines + msg.lines.length;
});
})();
</script>
</body>
</html>
client.html
<!DOCTYPE html>
<html>
<head>
<title>Websockets tail Server</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="info" class="trebuchet"></div>
<div id="tail" class="monospace selection"></div>
<script type="text/javascript">
(function() {
var lines = 0, notice = $("#info"), buffer = $('#tail');
var socket = io.connect('http://127.0.0.1:8000/');
socket.on('connect', function() {
console.log('Connected to stream');
});
socket.on('tail', function(msg) {
console.log("Message:");
console.dir(msg);
buffer.append(msg.lines.join('<br/>'));
buffer.scrollTop(lines*100);
lines = lines + msg.lines.length;
});
})();
</script>
</body>
</html>
Both the html files above are my clients and I want them to listen to my socket server but they are not but when I remove one of the clients,it works.
Any help will be appreciated
I'm working on a project where my job is to use Node.js and Socket.io to read a text file (contain 3 real time readings) and got the data in 3 variables, then send them to Socket.io and get them displayed on the website continuously without having to refresh it. I ran my codes, it did not give any errors, but it did not display anything on the website either. So I don't know what is wrong in my code. I need help with passing variables from Node.js to Socket.io and get them displayed on the my web page.
This is my server file:
var http = require('http').createServer(handler); //require http server, and cr$
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the htt$
http.listen(8080); //listen to port 8080
function handler (req, res) { //create server
fs.readFile(__dirname + '/index.html', function(err, data) { //read file inde$
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {
setInterval(function(){
var array = fs.readFileSync('report.txt').toString().split("\n");
var volt = (array[0]);
var power = (array[1]);
var temp = (array[2]);
socket.emit('volt',{'volt': volt});
socket.emit('power',{'power': power});
socket.emit('temp',{'temp': temp});
}, 1000);
});
index.html file :
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io('http://10.117.230.219:8080');
socket.on('volt', function (data) {
$('#volt').text(data.volt);
socket.on('power', function (data) {
$('#power').text(data.power);
socket.on('temp', function (data) {
$('#temp').text(data.temp);
});
</script>
<div id="volt"></div>
<div id="power"></div>
<div id="temp"></div>
</body>
You are missing some tags on your HTML page including HTML and head. You are also missing a closing )} for each socket.on(...) call in your script. This is what it should look like:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>
var socket = io('http://localhost:8080');
socket.on('volt', function (data) {
$('#volt').text(data.volt);
})
socket.on('power', function (data) {
$('#power').text(data.power);
})
socket.on('temp', function (data) {
$('#temp').text(data.temp);
})
</script>
</head>
<body>
<div id="volt"></div>
<div id="power"></div>
<div id="temp"></div>
</body>
</html>
This should do it.
I see this example on a precedent question on this link how to display a realtime variable in nodejs in HTML and i dont't see in real time the value of json file on client
despite the answer is defined correctly.
Moreover in the bash i launch the command node --inspect socketProva.js (socketProva.js is the name of my server file) and i see in the page of inspect this message "WebSockets request was expected". The strange thing is that the server show correctly in real time the data of json file but the communication with client it does not seem to happen.
Thanks for the answers and excuse for my bad english.
socketProva.js and index.html
var io = require('socket.io')(8080); // The port should be different of your HTTP server.
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));
io.on('connection', function (socket) { // Notify for a new connection and pass the socket as parameter.
console.log('new connection');
var incremental = 0;
setInterval(function () {
console.log('emit new value', obj);
obj = JSON.parse(fs.readFileSync('prova.json', 'utf8'));
socket.emit('update-value', obj); // Emit on the opened socket.
incremental++;
}, 1000);
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="messages"></p>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<pre id="incremental"></pre>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var socket = io('http://localhost:8080'); // Connect the socket on the port defined before.
socket.on('update-value', function (value) { // When a 'update-value' event is received, execute the following code.
console.log('received new value', value);
$('#incremental').html(value);
});
</script>
</body>
</html>
JSON File: prova.json
{
"football":{
"id": 1,
"home": "Liverpool",
"away": "Chelsea",
"score": "1-0",
"last scorer":"Gerrard"
}
}
If the prova.json don't change during time, there is no need to read it using fs.readFileSync. You can require it.
var obj = require('prova.json');
The full example is shown below: (remember I changed the client socket.io.js version)
server:
var io = require('socket.io')();
var data = require('./data.json')
io.on('connection', function (socket) {
console.log('connected:', socket.client.id);
setInterval(function () {
data.value = Math.random();
socket.emit('update-value', data);
console.log('message sent to the clients');
}, 1000);
});
io.listen(8080);
client:
<!DOCTYPE html>
<html>
<head>
<!-- this changed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="incremental"></div>
<script>
var socket = io('http://localhost:8080');
socket.on('update-value', function (data) {
console.log('received new value', data);
var $div = $('<div>');
$div.text(data.value)
$('#incremental').append($div);
});
</script>
</body>
</html>
And data.json:
{
"value": 1
}
Here is The Source Code Of my javascript moveing object,Could you just simply modify this Code or just Tell me Where should i Start from To use sockets here i know NodeJs on Beginner stage but there is no tutorial For Sockets So it's confusing How can i Just Send my Coordinates To sockets and Write a Response For that Coordinates.
<!DOCTYPE html>
<html>
<head>
<title>GameTest</title>
</head>
<body>
<style>
#img{
position:absolute;
top:0px;
left:0px;
width:50px;
height:50px;
}
</style>
<img id="img" src="hand.png">
<script>
var player=document.getElementById('img');
var x=0;
var y=0;
function movePlayer(event){
if(event.keyCode==39){
x+=2;
player.style.left=x+'px';
}
if(event.keyCode==37){
x-=2;
player.style.left=x+'px';
}
if(event.keyCode==38){
y-=2;
player.style.top=y+'px';
}
if(event.keyCode==40){
y+=2;
player.style.top=y+'px';
}
if(event.keyCode==40&&event.keyCode==37){
y-=2;
x+=2;
player.style.top=y+'px';
player.style.lef=x+'px';
}
getCoordinates(player);
}
document.addEventListener('keydown',movePlayer);
function getCoordinates(el){
while(el&&isNaN(el.offsetLeft)&&isNaN(el.offsetTop)){
x+=el.offsetLeft-el.scrollLeft;
y+=el.offsetTop-el.scrolltop;
el=el.offsetParent;
}
console.log( {top:y,left:x});
}
</script>
</body>
</html>
install socket.io
npm install socket.io
create server.js
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.on('coordinates', function (data) {
socket.emit('coordinates', data);
});
});
in index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
document.addEventListener('keydown',socket.emit({x:3,y:10}));
socket.on('coordinates', function (data) {
console.log(data);
//use data.coordinates here
});
</script>
In your addEventListener you can call getCoordinates or update coordinates in which you can call socket.emit(//cordinatees//);
I have read a lot of tutorial, and sample code to send data from a node.js class to an html page and show this data.
such as link1, link2,link3,link4,link5
and some others.
I am getting some data from UDP listener and need to send it after some processing to an html page to show it. here is my code:
The udp receiver:
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
var http = require('http'),
dgram = require('dgram'),
socketio = require('socket.io'),
fs = require('fs');
var html = fs.readFileSync(__dirname + '/html/showMap.html');
var app = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end(html);
io.sockets.emit('welcome', { message: 'Welcome!'});
}).listen( server_port, server_ip_address, function() {
console.log('Listening');
});
var io = socketio.listen(app),
socket = dgram.createSocket('udp4');
socket.on('message', function(content, rinfo) {
console.log('got message', content, 'from', rinfo.address, rinfo.port);
io.sockets.emit('udp message', 'content' /*content.toString()*/);
});
socket.bind(5001);
and my html page which is called 'showMap.html'
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Get Data</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="results"> This text will change </div>
<div id="date">sample another temp text</div>
<script>
// client code here
var socket = io.connect('localhost', {port: 8080});
socket.on('udp message', function(message) {
console.log(message)
document.getElementById("date").innerHTML = "My new text!";
});
socket.on('welcome', function(data) {
document.getElementById("results").innerHTML = data.message;
});
</script>
</body>
</html>
but by sending packet, html page has not changed.
Here is my console log of running code:
Atis-MacBook-Pro:startWithNode muser$ npm start
StartWithNodejs#1.0.0 start /Volumes/Project/Project/NodeJS/startWithNode
node index.js
Listening got message from 127.0.0.1 64047
What is wrong in my code?
I tested this locally. In your HTML file I made two changes and it worked.
1 - Replace io.connect('localhost', {port: 8080}); with io.connect('localhost:8080');
2 - There was a strange \u200b character at the end of the document.getElementById("date").innerHTML = "My new text!"; line. I deleted that and ended up with:
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Get Data</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<div id="results"> This text will change </div>
<div id="date">sample another temp text</div>
<script>
// client code here
var socket = io.connect('localhost:8080');
socket.on('udp message', function(message) {
console.log(message)
document.getElementById("date").innerHTML = "My new text!";
});
socket.on('welcome', function(data) {
document.getElementById("results").innerHTML = data.message;
});
</script>
</body>
</html>
Which replaces the content of results.
in this example you will be able to get JSON data from php file and send it to all connected clients.
RunThisFileThroughNodeJs.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
var request = require("request")
var url = "http://localhost/api/index.php";
events = require('events'),
serverEmitter = new events.EventEmitter();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
setInterval(
function(){
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
io.emit('chat message', body);
}
});
},5000);
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
Don't Forget to install express , request for nodejs
Now make this file i will call it index.html so the response of my file will be here.
index.html
<!doctype html>
<html>
<head>
<title>Prices API</title>
<script src="http://localhost/js/socket.io.js"></script>
</head>
<body>
<div id="price_list"></div>
<script>
var socket = io();
socket.on('chat message', function(msg){
document.getElementById("price_list").innerHTML = JSON.stringify(msg);
console.log(msg);
});
</script>
</body>
</html>