Blog

Simple Socket.io Example with Comments to Explain Event Emitting and Listening
Posted on July 15, 2015 in Node.js by Matt Jennings

server.js File in Root Directory of Node.js App

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

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

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

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

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

// Express is listening port 8000
var server = app.listen(8000);

// We pass the server object
var io = require('socket.io').listen(server);

io.sockets.on("connection", function(socket) {
    // This line console logs to
    // Terminal
    console.log("I'm using sockets!");

    // This line console logs to
    // Terminal the "socket.id" value
    console.log(socket.id);

    // This line executes when the
    // socket.emit("button_clicked", ...)
    // function executes from the
    // client side and the "data"
    // must be shown on the client side
    // as an object
    socket.on("button_clicked", function(data) {

        // When the button click event is
        // emitted from the client to
        // the server this line
        // console logs to Terminal AND
        // the "response" property name
        // matches the property name in
        // the client
        console.log("Someone clicked a button!\nReason: " + data.response);

        // Also after the client side
        // socket.emit("button_clicked",...)
        // event executes the
        // socket.emit("server_response")
        // method executes and data from the
        // "response" property is passed to
        // the client
        socket.emit("server_response", {response: "Sockets are the best!"});

    });

});

index.ejs File in views Directory of Node.js App

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="stylesheets/style.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">
        // triggers the connect event in our server
        // and if line below var socket = io.connect();
        // line doesn't work use this commented out line instead:
        // var sock = io.connect("https://www.mattjennings.net:8000");
        var socket = io.connect();

        $(function() {

            // On button click...
            $("button").on("click", function() {
                // When a button is clicked this line
                // emits to
                // the socket.on("button_clicked", ...)
                // method and the "response"
                // property name must appear
                // on the server (server.js)
                socket.emit("button_clicked", {response: "Because I want to learn about sockets!"});
            });

            // The socket.on("server_response") method
            // is executed when the
            // socket.emit("server_response") method is
            // executed server side, the
            // console log message appears in the
            // browser terminal and the "response" property
            // must "response" property name on the
            // server side
            socket.on("server_response", function(data) {
                console.log("The server says: " + data.response);
            });
        });
    </script>
    <title>Socket.io Node Package Test</title>
</head>
<body>

    <h1>Socket.io Node Package Test</h1>

    <button>I am a button!</button>

</body>
</html>

style.css File in static/stylesheets Directory of Node.js App

body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

Leave a Reply