Understanding Socket.io (#13)

Why Socket IO?

Before we dig into why I used socket.io, let’s first talk about what web sockets are.

Before Web Sockets

The web has been built around HTTP requests and responses. A client loads a web page, and then makes another request to the server and waits for a response every time it needs to change something. AJAX helped with making web pages feel more dynamic. We then started using long-polling to make the web allow users to interact more seamlessly.

What are web sockets?

Web Sockets provided a way for developers to create a lasting line of communication between the server and the client without using long-polling. It provided a way for the server to send information to the client before the client even requests it, and requires low overhead.

Back to why socket.io:

While there are a lot of libraries built on top of the Web Socket API, I chose to go with socket.io because it’s simple and the most widely-used. Companies like Microsoft, Zendesk and Trello use it, and with 43,000 stars on Github it’s backed by a lot of people in the developer community. More so, it also provides reliability for handling proxies, load balancers, anti-virus software, and even supports binary streaming.

How do I use Socket IO?

Using Socket IO is simple. For starters, you need two different node-packages on the server and the client.

npm install socket.io --save
npm install socket.io-client --save
const server = http.Server(app);
const io = require("socket.io)(server);
io.on("connection", socket => {});
import io from "socket.io-client";
const socket = io();

Events with Socket IO

“Alright, so far so good, now how do I send things back and forth without making HTTP requests” you ask?

Emitting an event:

To emit an event, from the front-end to the back-end, simply use:

socket.emit("name for data", data)

Receive an event:

To receive an event on the back-end, use:

socket.on(“name for data”, callback())

Broadcasting:

And finally, once the server receives this data, you want to emit it the desired response back to all clients. This is also called broadcasting.

io.emit("RECEIVE_MESSAGE", data.message)
socket.on("RECEIVE_MESSAGE", callback())

Conclusion

So in conclusion, here is a breakdown of the steps we followed:

  1. Install the socket.io and socket.io-client npm packages on the back-end and the front-end respectively.
  2. Establish a connection on both ends.
  3. Emit an event from the front-end.
  4. Receive this event on the back-end.
  5. ‘Broadcast’ a response to all clients.
  6. Receive the broadcast message on the front-end.

Thanks for reading through! 🚀 I hope this was helpful.

You can visit my website to learn more about me and get in touch

Social Media: twitter | github

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store