Ticker

6/recent/ticker-posts

Node.js app using Socket.IO

Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It's care-free realtime 100% in JavaScript.

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.



Test Node.js with socket.io

onclick="toggle(this);">







Run the app.js in server:
$ node app

Visit :8080 with browser in client side.


Next: Acknowledge from server

إرسال تعليق

0 تعليقات