WebSockets For Beginners. Part 2.

Tetiana Farhuts
7 min readMar 30, 2019

--

Build a Simple WebSocket Chat App with Socket.io and Express.js.

Prerequisites:

This article assumes that you have a basic understanding of Node.js and JavaScript.

For this chat-room, we will use a JavaScript library for real-time web applications, Socket.io which provides us with a client-side library that runs in the browser, and a server-side library for Node.js.

Step 1. Create a folder named “chat” on your Desktop. Inside this ‘chat’ folder create an index.js file.

Step 2. Run command npm init in your terminal to create a package.json file. This file will hold various metadata relevant to the project and it used to give information to npm that allows it to identify the project as well as handle the project’s dependencies.

Step 3. Install Express dependency with a command

npm install express --save

Fast overview of Express.js framework:

  • Node.js is a platform for building server-side event-driven i/o applications using javascript.
  • Express.js is a framework based on node.js for building web-application using principles and approaches of node.js.

In other words, Express.js makes it easier to set up and work with node. For instance, it has built-in methods that make routes easy to work with.

Step 4. Install Nodemon dependency with a command

npm install nodemon --save-dev

What is Nodemon? Nodemon looks for changes we made to our server-side code and restarts a server for us automatically instead of us having to type “node index.js” after every time we make a change.

What does it mean “-dev” in our npm command? When we run npm install ‘some package’ — save, it will automatically save this package in our package.json file under “dependencies” section.

npm install ‘some package’ — save-dev will save our package under “devDependencies” section that mostly contains files which are a convenience but not a necessity for our application.

To start a server with Nodemon you will have to run a command nodemonin your terminal, and it will automatically start the server and do all the work for you.

Step 5. Install Socket.io library with a command

npm install socket.io --save

Step 6. Set — up the server by adding the following lines of code in your index.js file:

Run nodemoncommand in your terminal to check if your server works. You should see “Listening on port 8080” in your terminal. But if you go to localhost:// 8080 in your browser, you will see a blank page with a single sentence “Cannot get / ”. Why is that? It is because we did not serve anything to our browser, so our app is missing a content file or a static file (HTML file).

Step 6. Set — up the static file.

Create a folder “public” and add an index.html file inside it.

Inside your index.htm add the following lines of code:

Now, go back to your index.js file and add one more line of code which will serve index.html file in our public folder to the browser.

app.use(express.static("public"))

Refresh your web-page (localhost:// 8080) and you will see the “Hi humans!” greeting.

Step 7. It’s about time to start working with a WebSockets! As mentioned before, we will use Socket.io library.

If you remember, in Section1 we discussed how WebSockets allows a persistent connection between the client and the server. It means that we have to create an open channel between the client side and the server side. We will have to install Socket.io on the client side and the server side.

Run npm install socket.io --save, for your server side and require socket in your index.js file.

const socket = require("socket.io")

Specify that you want this socket run on your server, by adding

const io = socket(server)

Now, socket.io is going to listen on the server and wait for the client (browser) to connect and then it will set up a socket connection with the client side.

Add the following lines of code to listen for when the connection is made

io.on(‘connection’, (socket)=>{    console.log(“Made socket connection")}

Now we have to connect our client side to the sockets. In index.html file pass a cdn link to the socket.io library.

<script    src=”https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js">
</script>

Step 8. Create “chat.js” file in your public folder and add

<script src=“/chat.js”></script>

to the bottom of the body in your index.html file.

When an index.html file is served to the browser, it will load the Socket.io library (thanks to the CDN link). Then it will run our chat.js file where we will establish the connection to our server and write all the logic for our chat.

In chat.js add following line of code:

const socket = io(window.location.origin) <- This will help us obtain the current URL/domain in the browser and make a connection between client and server.

At this point, if we refresh our webpage we can see the “Made socket connection“ and a weird combination of letters and numbers which represents socket.id (a unique socket) in our terminal. Open a new tab in your browser and go to the localhost:// 8080 and you will see one more “Made socket connection “ and socket.id in your terminal.

This means that we have established a connection between the client and the server and now we can freely pass the data between two of them.

Step 9. In your index.html body, create a form for your chat.

<div class="container">   <div id="chat-window">      <div id="output"></div>      <div id="answer"></div>   </div>     <input id="name" type="text" placeholder="Name"/>     <input id="message" type=“text" placeholder="Message" />        <button id="send" type="submit" name="action">          Send       </button></div>

In your chat.js bellow const socket = io(window.location.origin)create emitters which will send the data to the server when someone sends a message in our chat form and listeners which will listen to receive the data (messages from other clients) from the server.

Query the DOM and store the variables.

const message = document.getElementById('message'),      name = document.getElementById('name'),      btn = document.getElementById('send'),      output = document.getElementById('output'),      answer = document.getElementById(‘answer');

Add an event listener to the button. Once someone clicks the button, emit the event (a message in this case) and send it down the WebSocket to the server.

The actual message is a data (an object) which will be sent to the server.

btn.addEventListener("click", ()=>{  socket.emit('message', {      message: message.value,      name: name.value  });  message.value ='';})

Add an event listener for the event ‘keypress’ and emit (send) it to the server when someone is typing a message.

message.addEventListener('keypress', () => {   socket.emit('typing', name.value);})

Now, let’s add an event listener for the message from the server, and display the message in our chat window.

socket.on('message', (data)=>{    answer.innerHTML ='';output.innerHTML += '<p><strong>' + data.name + ': </strong>' +                           data.message + '</p>';})

Add an event listener (typing) from the server and display the typing.

socket.on('typing', (data) => {answer.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>';});

On our server side in our index.js file, we need to set-up listeners which will listen to the client side events (message, typing), and once it receives it, send it to the client.

Add the following lines of code inside your on “connection” function.

io.on("connection", (socket) => {     console.log("made socket connection", socket.id)// Receives message from the client and sends (emit) it to the client.     socket.on("message", (data)=>{          io.sockets.emit("message", data)     });// Handles typing event and broadcasts it to all the clients except of sender.      socket.on('typing', function(data){          socket.broadcast.emit('typing', data);      })})

Finally if your refresh your chat web-page and open the new tab in your browser and navigate to localhost://8080 you can see your chat app in action.

You can add some CSS styling to make it more visually appealing. If you got lost somewhere on the way, that’s okay, WebSockets can be very confusing at first. Check my GitHub repo for the reference, and feel free to clone it and modify it as you wish.

--

--

Tetiana Farhuts

I write about things related to programming, in the simplest way I can.