app.js
//$ npm install socket.io
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
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.sockets.on('connection', function (socket) {
socket.on('button update event', function (data) {
console.log(data.status);
//acknowledge with inverted status,
//to toggle button text in client
if(data.status == 'ON'){
console.log("ON->OFF");
socket.emit('ack button status', { status: 'OFF' });
}else{
console.log("OFF->ON");
socket.emit('ack button status', { status: 'ON' });
}
});
});
index.html
<html>
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
onclick="toggle(this);">
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);
socket.on('ack button status', function (data) {
console.log(data.status);
if(data.status =='ON'){
document.getElementById("buttonToggle").value="ON";
}else{
document.getElementById("buttonToggle").value="OFF";
}
});
function toggle(button)
{
if(document.getElementById("buttonToggle").value=="OFF"){
socket.emit('button update event', { status: 'OFF' });
}
else if(document.getElementById("buttonToggle").value=="ON"){
socket.emit('button update event', { status: 'ON' });
}
}
</script>
</body>
</html>
Next: Share common status for all clients
No comments:
Post a Comment