Introduction to the

Whether you’re building a chat app, a video sharing app, or even a video conferencing app, socket. IO provides a connection between your clients, allowing lightning-fast data transfers between them.

It consists of a client and a server, which handles different connections and information distribution. You should know that socket. IO is not a WebSocket, but a custom real-time transport protocol implementation built on top of other real-time protocols.

This article covers the basics of socket. IO, from setting up connections to connecting your client to the server.

What is WebSocket?

WebSocket is a network communication protocol that transmits data from client to server (and from server to client) once a channel has been established between them. This connection continues until the channel is terminated. Unlike HTTPS, WebSocket allows two-way data transmission.

WebSocket can be used to build anything from real-time trading applications to chat applications, or just about anything that requires efficient, real-time data transfer.

What are sockets and socket. IO?

A socket is a connection implemented between specific points in a network. A connection in a socket, once created, persists until it is terminated. Socket connections can be server to client, client to server, or between two clients or servers.

Socket. IO is a JavaScript library that works in a similar way to WebSockets. Data transfer is done over an open connection, allowing real-time data exchange. Each connection, also known as a socket, consists of two parts. Server side and client side. Socket. IO uses Engine. IO to connect the server to Engine.

Most of the data transfer in socket.io is done in JSON (JavaScript object notation), so we’ll use the JSON format in this article.

Installation and Setup

Since socket. IO requires both the server and the client to connect, we will install both (server and client) starting on the server and then moving to the client.

The server side

Make sure you have Node.js and the Node package Manager (NPM) installed on your system. If not, go to the Node.js website to learn more about installation.

From your command line, run the following command.

npm install express Socket.io 

Copy the code

This will install the necessary dependencies.

The next step is to set up our server. Go ahead and ask for socket. IO, Express, and HTTP modules in your index.js file, as shown below. We’ll use the HTTP module to create our server instead of Express to easily pass our server to socket.io.

const express = require("express");
const http = require("http");
const socketio = require("socket.io");

const app = express();

const PORT = process.env.PORT || 5000;

const server = http.createServer(app);

io = socketio(server);

server.listen(PORT, () => {
  console.log(`server running at port ${PORT}`);
});

Copy the code

As shown above, we successfully created our server. We can start our server by running the following program.

node index.js

Copy the code

Our server should be up and running on port 5000. Notice that our server is passed to socket.io.

The client

For the client setup, let’s import the socket. IO script into our index.html file.

<script src="/socket.io/socket.io.js"></script>

Copy the code

Continue to connect your client and server as shown below.

=let ENDPOINT = "http://localhost:5000"
let socket = io.connect(ENDPOINT);
=
Copy the code

Or, if you use React, you can install socket.io-client for your client.

npm install socket.io-client

Copy the code

You can then proceed to import and create a connection like this.

import React from "react";
import io from "socket.io-client";

let ENDPOINT = "http://localhost:5000"
let socket = io(ENDPOINT);

Copy the code

Socket connection and disconnection

We have successfully set up our server side and client side. Now, once the client is connected, we are notified of the connection on the server side. Socket. IO helps us do this with the connection.

io.on("connection", (socket) => {
  // your code snippet 
})

Copy the code

This event, equipped with a callback function, is fired when a connection occurs.

For more complex applications, you may want to create specific rooms for different groups of users. This functionality can be easily implemented using socket.io. Once the connection is made, you can join specific rooms using the Join method.

io.on("connection", (socket) => {
  let roomID = 2436
  socket.join(roomID)

})

Copy the code

A disconnection event is triggered as soon as a disconnection occurs.

io.on("connection", (socket) => {
  socket.on("disconnect", () => {
        });
})

Copy the code

Event launch and broadcast

Socket. IO allows the user to emit events and listen for them on the other side. Event emission can occur on both the server and client sides. For example, an “join” event can be issued on the client side during a connection.

Socket. emit("join", {name: "Peter Paul"}, (err) => {if (err) {alert(err); }});Copy the code

Notice that this event is emitted with a JSON payload that contains the name of the user currently joining the connection.

Continue processing this event on the server side.

socket.on("join", ({ name }, callback) => {
    if (error) {
      callback(error);
    } else {
      let roomID = 2436
      socket.join(roomID)
      console.log(name)
      });

Copy the code

During event processing, you can also choose to broadcast a message to everyone in a particular room.

socket.on("join", ({ name }, callback) => { if (error) { callback(error); } else { let roomID = 2436 socket.join(roomID) socket.broadcast.to(roomID).emit("adminMessage", { name: "admin", content: `${name} has joined`, }); }});Copy the code

All of our server-side code should look like this at this point.

const express = require("express");
const http = require("http");
const socketio = require("socket.io");

const app = express();

const PORT = process.env.PORT || 5000;

const server = http.createServer(app);

io = socketio(server);

io.on("connection", (socket) => {
   socket.on("join", ({ name }, callback) => {

    if (error) {
      callback(error);
    } else {
      let roomID = 2436
      socket.join(roomID)
      console.log(name)
       socket.broadcast.to(roomID).emit("adminMessage", {
             name: "admin",
             content: `${name} has joined`,
         });
      });

    socket.on("disconnect", () => {
         });
})

server.listen(PORT, () => {
  console.log(`server running at port ${PORT}`);
});

Copy the code

The client structure should look like this.

let ENDPOINT = "http://localhost:5000" let socket = io.connect(ENDPOINT); Socket. emit("join", {name: "Peter Paul"}, (err) => {if (err) {alert(err); }});Copy the code

Debug and record

Socket. IO comes with a very powerful debugging tool called Debug. Before Debug was introduced, socket. IO used to log everything to the console, which most users found annoying. Later, they took a new step and didn’t record anything by default.

You can optionally view this information when using a browser by providing the Debug environment variable or the localstorage.debug property.

For the console, it does as follows.

DEBUG=* node yourfile.js

Copy the code

* Helps you see what information is available.

For browsers, it works like this.

localStorage.debug = '*';

Copy the code

conclusion

Socket.io, for all its simplicity, has become a prime choice for developers building applications that require real-time data transfer. With almost all modern browsers supporting WebSocket, socket. IO is expected to get even bigger.

Now that you’ve mastered the basics of socket.io, I recommend working on a different project with the same concepts as above to hone your skills and gain a clearer understanding of the topic.

The postReal-time data transfer with Socket.ioappeared first onLogRocket Blog.