This example create a simple web app to receive the status of a toggle button from client.
Before using Socket.IO on your Node.js app, run the command to install:
$ npm install socket.io
app.js run in server side:
//$ 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);
});
});
index.html, it will be sent to and run on client side.
<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);
function toggle(button)
{
if(document.getElementById("buttonToggle").value=="OFF"){
document.getElementById("buttonToggle").value="ON";
socket.emit('button update event', { status: 'OFF' });
}
else if(document.getElementById("buttonToggle").value=="ON"){
document.getElementById("buttonToggle").value="OFF";
socket.emit('button update event', { status: 'ON' });
}
}
</script>
</body>
</html>
Run the app.js in server:
$ node app
Visit <server IP>:8080 with browser in client side.
Next: Acknowledge from server
No comments:
Post a Comment