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).
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.
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 ‘