Node.js Socket.io Introduction and Getting Started 01

Video Tutorial

Getting Started

Socket.io is a Library for Connecting a Client(s) to a Server using the Client/Server Architecture while it is a wrapper around WebSockets For Node.js, it is super easy and simple to use especially when dealing with chat messages or Real-time data.

A Socket represents a single connection between a client and a server where each the client or server can send and receive data at the same time where Library is based on an event-driven system, emit and listen for specific events to be triggered.

Since we are going to use Node.js so you need to make sure to install Node.js and also have a code editor (VSCode or Atom).

Here is the project structure that we are going to work on during this series.

--dist
--src
app.js ///< The Client 
server.js ///< The Server 
package.json ///< Nodejs JSON

Now For creating the socket.io application, we need two node.js running instances, one for the client (app.js) and the other instance for the server (server.js) there for let’s install the socket io and express libraries.

npm install socket.io socket.io-client express --save

As you can see we also need the client library so (the socket.io library is for creating the server side) and (socket.io-client is for creating the client side) and express is for creating the server since we need to provide an HTTP Server to the socket.io to listen to and a specific host and port.

Basic Socket.io Server

The server is the main point in the connection architecture without a server there will be no data transmission between one user and another (one or more clients) so you send a piece of data to the server the server handles the received data (for ex: store in a database) the forward it to the destination client(s) this is how it works with sockets (you can use peer to peer but this is a different thing).

You should also me already familiar with creating express apps on Node.js if you are not Here is a full course series which explains Node.js and express in action and many other things you need to learn before diving into working with WebSockets.

const express = require("express");
const app = express();
const port = 3000;
const http = require("http").createServer();
const io = require("socket.io")(http);
//Listen for a client connection 
io.on("connection", (socket) => {
    //Socket is a Link to the Client 
    console.log("New Client is Connected!");
    //Here the client is connected and we can exchanged 
});

//Listen the HTTP Server 
http.listen(port, () => {
    console.log("Server Is Running Port: " + port);
});

Well, this basic server is responsible for listening for a new client connection and once it’s made the server is going to log a message to the console saying that a new client has been connected.

On Socket.io everything is based on Events and Callbacks so let’s say that you want to send a message from the server to the User, therefore, you need to emit an event on the server with the message you want to send and on the client’s side you register a listener for this specific event and when it occurs you run a callback.

io.on("connection", (socket) => {
    //Socket is a Link to the Client 
    console.log("New Client is Connected!");
    //Here the client is connected and we can exchanged 
    //Send Message 
    //We need to use the Socket (the link between the server and the connected user(s)).
    socket.emit("welcome", "Hello and Welcome to the Server");
});

Once the user is connected to the Server the server sends him a welcome message by emitting a welcome event, now let’s create the client side and listen for this specific event in order to receive the message, so between the Server & the Client you need to build an API.

Basic Socket.io Client

On the client side, we are going to use socket.io-client library since it’s responsible for the client’s API, open the app.js.

const io = require("socket.io-client");
//First Connect to the Server on the Specific URL (HOST:PORT)
let socket = io("http://localhost:3000");
//Now Listen for Events (welcome event).
socket.on("welcome", (data) => {
   /*For the listener we specify the event name and we give the callback to which be called one the 
   event is emitted*/
   //Log the Welcome message 
   console.log("Message: ", data);
});

You call the on method to register a callback with a specific event name, the callback takes the data which to be received as a parameter in this case the data is a plain string but sockets are capable of sending and receiving any type of data (Binary Blob, JSON, Media…).

Any connected client to the server is going to receive the welcome message when he/she connects to the server, but socket.io provide you with a bit more advanced API to create chat like systems where two users can chat together privately without letting the others know about it (Creating Rooms).

Let’s try to run both the server and the client now.

Run Server first.

node server.js

The Client App which itself gonna tries to connect to the server on the localhost port 3000 (whatever you specify on the server you need to change on the client’s app).

node app.js

One the client’s instance is running you will get the following logged to you on both sides (Server & Client) consoles.

//Server 
New Client is Connected!

//Client 
Hello and Welcome to the Server

That means our server is accepting the connection and sending an event alongside a welcome message to the client where the client is able to receive it and handle it properly so everything is connected together.

What’s Next

Now since you have a basic idea about how everything works and how data can be transmitted between a server and a client or vice-versa, in the next tutorials we will dig deeper and take close look on more advanced topics about data exchange and connect/disconnect and handling multi-user alongside real word example (chat app).

No Comments Yet