July 17, 2015

367 words 2 mins read

SocketIO IRC-style Tutorial – Part 2 – Getting started

This is the 2nd post in a multi-part tutorial series on Socket.io. See Part 1 here.

As with all things in life, code is in a constant state of change. Eventually, this tutorial series will be improved, but so that we can all stay on the same page, let’s start with the same version of code. You can go to ShakataGaNai/socketio-sample/d9b7bcc132 to browse the exact working copy this tutorial is based off of. You should download version d9b7bcc132…zip file as well, to work with locally. The repository only has three important files; app.js — which contains the NodeJS server application, index.html — which is our client side (in browser) application, and package.json — which provides some basics about this app, including the dependencies.

The instructions (README) are easy enough.

  • npm install — Installs dependencies, in this case only Socket.IO
  • node app.js — Launch the server app, defaults to port 3000
  • Open index.html in your browser.
With any luck you can type into the webpage and have a conversation with yourself. It should end up looking like the previously included screenshot. For each user who joins you’ll see a “Server” notice that someone has joined. Each user will be assigned a random nickname and will be able to chat.

Some features you can try out:

  • /nick NEWNAME — Change your nickname
  • /nick server — Server will reject your nick change (server protected words)
  • #FF0000 — Enter any valid color code and the server will change everyones background color
  • Joining & Quits are tracked
  • Sending messages
I’m aware this isn’t a very rich chat system, but it’s much more in-depth than most of the tutorials out there, which is why I wrote it in the first place. One could argue that it is a minimum viable project if all you want is a one room chat system. Before you complain too much, flip back to your terminal (where you launched app.js) and you’ll see something like the image on the right. All the actions are also documented on the server side, for debugging/diagnostic purposes.

At this point you have a fully functional chat application you could potentially post publicly. In Part 3 I’ll start explaining the server code (app.js).