Socket.io with Node.js

Socket.io is an open-source JavaScript framework which is available as a Node package. It is based on WebSockets technology. Socket.io enables real-time, bi-directional, event based communication. JSON format is used for data communication

Features

  • Reliability: Socket.io is designed to work on every platform whether it is mobile or desktop.
  • Speed: It is fast.
  • Simple API: It is easy to use. API methods are same both on client and server.

The official website goes in more details and have a very nice documentation, which you can find on this link.

WebSockets

WebSockets is a standardized browser based technology. This technology allows direct 2-way connection b/w client and server.

This makes it easy to build real-time apps because server can dynamically push new data to connected clients whenever there is new data available.

Socket.io was built to make it easy to work with websockets connections. Just like, JQuery is a simplified wrapper around DOM-javascript. The other reason was to eliminate some natural web-socket connection problems.

Socket.io Setup

Please check this link for latest setup information from official Socket.io website. It is very simple and following are steps I performed to setup in this application.

For some of the earlier steps, like how to setup a Git Repo, Node in general, or basic development environment setup, you can read my earlier posts, where I wrote about those in details.

1. Install socket.io using npm

2. Add a reference to socket.io.js file to index.html

Here is some info from readme file.

3. Setup socket.io on Node server side

You can clone the source-code of this repo. However, here is the wiring part of socket.io.

Connection Test

Now, if we run our app and open the index page, our server will fire the connection event, and that’s it. Connection is working.

Send and Receive Messages

Now, lets see how can we send and receive messages from the server to the client, and vice versa:

  • We use emit and on methods as our primary methods for handling events in socket.io.
  • We will setup emit and on methods on server as well as on client.

Server

Client

Result

Summary

Node.js way of programming and ability to use JavaScript both on front-end and back-end is really fun to work with. I have used SignalR as well on .NET core web application but socket.io make it really easy and natural. The official website of socket.io have a very nice tutorial you can read to progress. I will use socket.io in my upcoming posts, so this will serve as a starting point.

You can clone the git repo from this link and if you are interested in Node. then you can read my other posts on the topic. Till next time, Happy Coding.

References


Discover more from Hex Quote

Subscribe to get the latest posts sent to your email.

Discover more from Hex Quote

Subscribe now to keep reading and get access to the full archive.

Continue reading