Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is an example of the simplest possible example?

What is an example of the simplest possible example?


So, I have been trying to understand lately, but I am not a supergreat programmer, and almost every example I can find on the web (believe me I have looked for hours and hours), has extra stuff that complicates things. A lot of the examples do a bunch of things that confuse me, or connect to some weird database, or use coffeescript or tons of JS libraries that clutter things up.

I'd love to see a basic, functioning example where the server just sends a Message to the client every 10 seconds, saying what time it is, and the client writes that data to the page or throws up an alert, something very simple. Then I can figure things out from there, add stuff I need like db connections, etc. And yes I have checked the examples on the site and they don't work for me, and I don't understand what they do.

Problem courtesy of: Cocorico


Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

Just because I feel nice today:




    var http = require('http'),
        fs = require('fs'),
        // NEVER use a Sync function except at start-up!
        index = fs.readFileSync(__dirname + '/index.html');
    // Send index.html to all requests
    var app = http.createServer(function(req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
    // server listens to our app
    var io = require('').listen(app);
    // Send current time to all connected clients
    function sendTime() {
        io.emit('time', { time: new Date().toJSON() });
    // Send current time every 10 secs
    setInterval(sendTime, 10000);
    // Emit welcome message on connection
    io.on('connection', function(socket) {
        // Use socket to communicate with this particular client only, sending it it's own id
        socket.emit('welcome', { message: 'Welcome!', id: });
        socket.on('i am client', console.log);
    Solution courtesy of: Linus Gustav Larsson Thiel


    View additional discussion.

    This post first appeared on Node.js Recipes, please read the originial post: here

    Share the post

    What is an example of the simplest possible example?


    Subscribe to Node.js Recipes

    Get updates delivered right to your inbox!

    Thank you for your subscription