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

What is an example of the simplest possible Socket.io example?

What is an example of the simplest possible Socket.io example?

Problem

So, I have been trying to understand Socket.io 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 socket.io site and they don't work for me, and I don't understand what they do.

Problem courtesy of: Cocorico

Solution

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:

index.html



    
        

    app.js

    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'});
        res.end(index);
    });
    
    // Socket.io server listens to our app
    var io = require('socket.io').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.id });
    
        socket.on('i am client', console.log);
    });
    
    app.listen(3000);
    
    Solution courtesy of: Linus Gustav Larsson Thiel

    Discussion

    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 Socket.io example?

    ×

    Subscribe to Node.js Recipes

    Get updates delivered right to your inbox!

    Thank you for your subscription

    ×