Blog

Socket.io Example that does a Full Broadcast of a Counter that Increments by One
Posted on July 16, 2015 in Node.js by Matt Jennings

server.js Server File

// require express and path
var express = require("express");
var path = require("path");

// Create express app
var app = express();

// Static content
app.use(express.static(path.join(__dirname + "/static")));

// Setting up ejs and view directory
app.set("views", path.join(__dirname + "/views"));
app.set("view engine", "ejs");

// Rooute route to rend the index.ejs view
app.get("/", function(req, res) {
    res.render("index");
});

app.get("/reset", function(req, res) {
    res.redirect("/");
});

// Express is listening on port 6789
var server = app.listen(6789, function() {
    console.log("Node.js is running on port 6789!");
});

var io = require("socket.io").listen(server);

// Setting the counter to 0 which is
// OUTSIDE of "io.socket.on(...);"
var counter = 0;

io.sockets.on("connection", function(socket) {
    console.log("Sockets are running!");

    // Listens for the "client_count" emit
    // from index.ejs before taking an
    // action on server.js
    socket.on("client_count", function(action) {
        // Increments the counter by 1
        // starting with zero
        counter++;
        console.log(counter);

        // "io.emit(...)" does a
        // full broadcast of this
        // server.js emit so that all
        // clients viewing the website
        // will see "counter" has
        // incremented by 1
        io.emit("server_counter", {response: counter});
    });

    // Listens for a "client_reset_count"
    // emit from index.ejs
    socket.on("client_reset_count", function(action) {

        // Assigns "counter" to zero
        // when the "client_reset_count"
        // emit is sent from index.ejs
        counter = 0;

        // Sends a full broadcast
        // emit from server.js to
        // index.ejs which sets
        // the "zero" property value
        // of "counter" to 0
        io.emit("server_reset_count", {zero: counter});
    });

});

index.ejs View File

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>The great button game</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css"/>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>

    <script type="text/javascript">
       // Assigns "socket" to the correct value
       // OR can sometimes use the commented out
       // line below:
       // var socket = io.connect();
       var socket = io.connect("https://www.mattjennings.net:6789");

        $(function() {

            $("button").on("click", function(e) {
                e.preventDefault();

                // When button element clicked
                // sends  a "client_count" emit
                // from index.ejs to server.js
                socket.emit("client_count", {action: "Button clicked"})

            });

            // Listens for the "server_counter"
            // emit coming from server.js
            // before taking an action
            socket.on("server_counter", function(action) {
                // the "action.response" value
                // is passed from the "server_counter"
                // emit from server.js and this value
                // is assigned to "counter" on server.js
                // which starts at 0 and increments
                // by 1, all on server.js
                $("#count").html(action.response);
            });

            $("#reset").on("click", function(e) {
                e.preventDefault();

                // Sends a "client_reset_count" emit from
                // index.ejs to server.js whenever the
                // "#reset" link is clicked
                socket.emit("client_reset_count", {action: "Counter reset"});
            });

            // Listens for a "server_reset_count"
            // full broadcast emit from server.js
            socket.on("server_reset_count", function(action) {
                // On a "server_reset_count"
                // full broadcast emit from "server.js"
                // sets the "#count" value to
                // the "action.zero" value
                // which is defined on "server.js"
                // as "counter", which is also assigned
                // to zero on server.js
                $("#count").html(action.zero);
            });

        });
    </script>
</head>
<body>

<div id="wrapper">

    <h1>This button has been pushed <span id="count"></span> time(s)</h1>

    <p>Push the button to update the count!<br /><button>Push the epic button</button></p>

    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p><a id="reset" href="reset">RESET COUNT</a></p>


</div>

</body>
</html>

Leave a Reply