Simple chat application with NodeJS and Socket.IO

This week has been about playing with sockets for some data communication between C# and Javascript. While getting to grips with the basics of the socket libraries, I created a simple chat application to run on my local machine. It served well as a basic introduction to sockets and the NodeJS package, so I thought I’d share my code with some explanations so others can see how easy it is to get involved with this sort of thing.

What do we need?

Before we begin this project, we need to have the NodeJS package installed on our computer. If you don’t have NodeJS installed, you can download it here. From NodeJS, we’ll be using the web framework ‘express’, and later, Socket.IO.

Setting up NodeJS – express dependency

Once you have downloaded and installed NodeJS, you need to install two dependencies from it, ‘express’ and ‘socket.io’. To install these, open up your command line terminal.

To install ‘express’, type, or paste, the following:
npm install –save express@4.10.2

Before we can install socket.io, we now need to create some files.

What files do we need?

For this project, we’re going to create three files, a JSON file, Javascript file and an HTML file. Neither will have much in them, but together they’ll form the basis for our basic chat application. I would recommend working in an empty directory for this project, but you’re free to save these where ever you like providing their in the same folder together.

package.json

The first file we’re going to create is our package JSON file. This give details about our project and contains the name, version, a description and any dependencies. An example is given below, feel free to copy/paste it into a notepad file. Just remember to save that file as “package.json”.

{
    "name": "Socket Chat App",
    "version": "0.0.1",
    "description": "A simple chat application test",
    "dependencies": {}
}

index.js

The second file we’ll create is our Javascript file. To begin with, this will need to be basic and won’t include our Socket stuff, as we haven’t yet installed the socket.io dependency (don’t worry, we will in a bit though). This Javascript file will hold our Javascript code for the sockets once we have them installed and ready to go.

var application = require('express')();
var http = require('http').Server(app);

application.get('/', function(req, res) {
    res.send('Hello world!'); //Print hello world to the HTML file to begin with
});

http.listen(3000, function() {
    console.log('We are listening on port 3000'); //Log a successful connection in the terminal
});

First test

Before you can run a test, you need to turn the server on. Do this in the terminal by navigating to the directory in which you’ve saved everything, and typing (or pasting):
node index.js
If everything has gone correctly so far, you can now point your browser to your local host (http://localhost:3000) and you should see the text ‘Hello World’ displayed, with the terminal displaying the log message (see below).

If everything has worked so far, the terminal should display this text.

If everything has worked so far, the terminal should display this text.

index.html

So far we have the Javascript file simply printing the ‘Hello World’ text to the browser window. However, if we did that for our entire webpage our Javascript would get very messy very quickly. So instead we’ll create an HTML file to hold our HTML code. Create a blank HTML file and populate it with the following mark-up:

<html>
    <head>
        <title>My Socket.IO Chat App</title>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font: 13px Helvetica, Arial; }
            form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
            form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
            form button { width: 9%; background: rgb(252, 101, 0); border: none; padding: 10px; }
            #messages { list-style-type: none; margin: 0; padding: 0; }
            #messages li { padding: 5px 10px; }
            #messages li:nth-child(odd) { background: #777; }
        </style>
    </head>
    <body>
        <ul id="message"></ul>
        <form action=""> 
            <input id="b" autocomplete="off" />
            <button>Send Message</button>
        </form>            
    </body>
</html>

Modify index.js

Now that we have an HTML file to work with, we need to modify the index.js file to call this page, and not simply send ‘Hello World’. To do this, we change the function called in application.get, as below:

application.get('/', function(req, res) {
    //res.send('Hello World!'); //No longer needed - commented out
    res.sendFile(__dirname + '/index.html');
}

Second test

If you reset the terminal by hitting Control-C and rerun the previous command (node index.js), then refresh the local host, you should now see something close to the image below.

After the second test, your webpage should look like this.

After the second test, your webpage should look like this.

Installing Socket.IO

We’re now ready to install and integrate the sockets so we can begin chatting. The first thing we need to do is install it, which is done as so:

To install ‘socket.io’ type, or paste, the following:
npm install –save socket.io
If you have difficulties installing Socket.IO, I made a post here which may help fix your issues.

Modify index.js (again)

Now that we have Socket.IO installed, we need to make use of it in our Javascript file. To do this, we need to add the following code to our file to open the sockets and emit messages we receive.

var sIO = require('socket.io')(http); //Put this with your other variables

//Add this to the end of the document
sIO.on('connection', function(socket) {
    console.log('Someone connected, yippee!');
    socket.on('chat message', function(msg) {
        sIO.emit('chat message', msg); //Display the incoming message
    });
});

Modify index.html

Now we have sockets installed and can call them in the Javascript file, we can now call upon them in our HTML file and begin chatting. To do this, add the following code above the ‘‘ tag in the index.html file.



<script>
    var mySocket = sIO();

    $('form').submit(function() {
        mySocket.emit('chat message' $('#m').val());
        $('#m').val(''); //Reset the message box to be blank
        return false;
    });

    mySocket.on('chat message', function(msg) {
        $('#messages').append($('<li>').text(msg));
    });
</script>

Finished

If you now log onto your local host from two windows, you can now chat between them. Alternatively, you can give someone access remotely to the server this resides on and you can chat between them.

Finished - now you can chat using sockets.

Finished – now you can chat using sockets.

Of course this is just a basic chat application, but from here you can move onto bigger and better things. For example, you could implement the use of usernames, private messages and more. Why not give it a try and let me know how you get on in the comments?

Helpful references

This site here (Socket.IO) gives a more in-depth tutorial into doing a basic chat application, as well as greater explanation of the little pieces we’ve linked together here. Worth a look if you get stuck on something that I haven’t explained here.

Leave a Reply

Your email address will not be published. Required fields are marked *