Web Sockets 101
Motivation
While at the Flatiron School I heard about web sockets, through a project some of my classmates built. At that time they were building a card against humanity game, which used web sockets for the real-time feature. Ever since then web sockets were in the back of my mind. This week I finally decided to take a dive into web sockets and learn about its fundamentals and create a chat application. The following will walk you through understanding web sockets fundamentals and putting it to work using Socket.io.
Background
Web Sockets is a technology that allows the server and client side of an app to talk to each other back and forth with no interruption. This technology makes real-time data transfer possible, allowing for the creation of applications such as chat and stock apps. The magic happens through a socket or port through which data goes in and out of.
The World Wide Wed uses the HTTP protocol, but it has its limitations. An HTTP protocol handles its connections by allowing one-way communication, for instance, data is transferred through a port and then the port closes without waiting for a response. Web sockets come to solve this issue by allowing the port to remain open after delivering the data and waiting for a response to delegate to the client/server. Another issue they solve is that of fetching a server for new information, the client would have to refresh the browser for new data, but with sockets, the port remains open so the data is delegated as its updated.
Example
After providing you a brief introduction and background on Web Sockets and telling you how they work, let’s see them in action. The following is a simple chat application which allows for many clients who can send and receive messages in real time. The chat application uses a popular web sockets library called Socket.io and a MLab Mongo DB in cloud database for storing the messages. All the source code for the following can be found here.
Setting up Web Sockets in client-side
Setting up web sockets in the client side is pretty straight forward. We have to first add the script tag <script src=”/socket.io/socket.io.js”></script>, this script tag is included once we run npm install socket.io on our project repo. To start the sockets on the front end we need the following lines of code:
var socket = io()
socket.on('message', addMessage) //check for the message event(event listener)
The io() initializes the library and the socket.on(..) turns on the sockets and constantly listens for specific events. In a chat application the event it listens for is, for a message.
Setting up Web Sockets in the back-end
In the back-end, the set up is a bit different. First, we have to require the socket.io library, in most cases with a parameter. We also have to turn on the web sockets by using the io.on(…) as seen below.
var io = require('socket.io')(http)
io.on('connection', (socket) =>
{ console.log("A user connected");})
In order to send the events that the frontend listens to, we have to use the io.emit(..) function. In a chat application, the emission will be actual messages. As the backend receives a message and saves it, the message is sent back to the client as this takes place, creating this real-time feature.
app.post('/messages',(req,res) => { //message is posted
var message = new Message(req.body)
message.save((err) => { //message saved
if (err) //, if error occurs send 500 server error
sendStatus(500)
io.emit('message',req.body) //if successfully saved emit the message
res.sendStatus(200) //send ok status 200
})})
If you’d like to have a demo of the application you are welcome to test it using the code on GitHub. Clone the repo and then run node server.js, then open two windows one regular and one incognito, navigate to localhost:3000 on both and see the chat application in action, by sending messages back and forth.
Summary
In this blog we explored web sockets and how they work. We learned that http request are limited and aren’t enough to build complex modern web applications. In this blog we went through a quick set up of web sockets in both the client side and back-end.