DEV Community

Cover image for WEBSOCKETS
renam singla
renam singla

Posted on

WEBSOCKETS

The WebSocket API makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive responses without having to poll the server for a reply

The WebSocket protocol is the underlying communication standard, while the WebSocket API is the interface that developers use in client-side applications (like web browsers) to leverage the capabilities of that protocol.

  • The client and the server can communicate without the handshake.
  • The communication needs to started by the client generally.
  • WebSocket servers are used for real time communication (provide full duplex communication).
  • It is persistent in nature, once connection made, it remains.

Sockets are -

  • In-build
  • A library called Socket.IO

SOCKET.IO

  • It is build on WebSocket only.
  • Socket.IO is a library that enables low-latencybidirectional and event-based communication between a client and a server.
  • In this http also works along with the sockets functionality.
  • Socket.IO internally uses sockets creating WebSocket connections and using eventListeners for its working. That is-
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");

// Connection opened
socket.addEventListener("open", (event) => {
  socket.send("Hello Server!");
});

// Listen for messages
socket.addEventListener("message", (event) => {
  console.log("Message from server ", event.data);
});
Enter fullscreen mode Exit fullscreen mode

Socket.IO Working-

Client and server connects through a pipeline, not requiring handshake, where server can send data to the client and client can send data to server as well.

Hence, not requiring get or post request for communication

And that very pipeline is called SOCKET

  • Each socket has an id to refer to the client connected to the server.

On the server side,

server manages 1) request response cycle and 2) sockets as well.

To use sockets on server side-

npm install socket.io
Enter fullscreen mode Exit fullscreen mode

The socket(pipeline) is used on the client and the server side with the help of the object of socket having their id

💡

IO -The group of sockets on server side is called io

Hence , when message is send to the io , all the connected cllients receives the message with different id , called BROADCASTING.

system

NOTE-

When we use sockets, we cannot start express server i.e. app.listen() as it creates a new HTTP server

INITIALIZING SERVER (backend)-

const express = require("express");
const { createServer } = require("http");  //require http
const { Server } = require("socket.io");   //require server from socket.io

const app = express();
const httpServer = createServer(app);   //http gets a refrence of the app
const io = new Server(httpServer, { /* options */ });

io.on("connection", (socket) => {
  // this function works when client is connected to the server
});

httpServer.listen(3000);
Enter fullscreen mode Exit fullscreen mode

-Whenever a client connects to the server , it triggers the event connection , hence using-

io.on("connection",(socket)=>{ //we get an object of socket
            console.log("client connected");
});
Enter fullscreen mode Exit fullscreen mode

USE SOCKET.IO ON FRONTEND-

By default, the Socket.IO server exposes a client bundle at /socket.io/socket.io.js when the server is started.

STEPS-

1- Create a public folder and make index.html inside it.
2- Send the file on the server-

const path=require('path')
app.use(express.static(path.join(__dirname,'public'));
Enter fullscreen mode Exit fullscreen mode

3- The first initiation is to de done by the client by adding the bundle to the index.html file in the script tag by-

<script src="/socket.io/socket.io.js"></script>
Enter fullscreen mode Exit fullscreen mode

4- io named function now will be available to the browser

browser

5- To connect the client to server- io() function needs to be called by the browser, meaning a pipeline is established between the client and the server
6- To do the above step we made js file in the public folder for the frontend.

//in script.js file in the public folder(frontend)
const socket= io();
Enter fullscreen mode Exit fullscreen mode

socket can be accessed from the backend and the frontend as well, they would have same socket.id hence establishing the pipeline.

Sockets Work through Event Triggering from both ends-

doc

(source- documentation of socket.io)

emit function is used to send the message with the name of the event

on function is used to receive (or capturing the event) the message by matching the event name

  • All the event trigger written in backend are coded inside the io.on() function only where we made "connection" .

CREATE CHAT APPLICATION-

  • ON FRONTEND- create an input and send message button-

frontend

  • In script.js file of frontend send this input message to the server when button is clicked-
btn.addEventListener('click',(ev)=>{
    socket.emit('chat',{
        data: msg.value //here msg is the id of the input
    })
})
Enter fullscreen mode Exit fullscreen mode
  • To receive this message on the server-
io.on("connection", (socket) => {
  console.log("client connected", socket.id); 

//   all the event triggering is written in the io.on() function

    socket.on('chat',(chatdata)=>{
        console.log(chatdata.data)
    })
})
Enter fullscreen mode Exit fullscreen mode
  • To send this message on all the clients including from where it was received we use-io.emit()
io.emit('grpchat',chatdata.data)
Enter fullscreen mode Exit fullscreen mode

and the frontend can receive the message using socket.on() and match the event name and display on the viewport using ul and li -DOM concept.

  • To broadcast this message to all the clients except from where it was send to the server, we use- socket.broadcast.emit()
socket.broadcast.emit('grpchat',chatdata.data)
Enter fullscreen mode Exit fullscreen mode

OUPTUT FOR BROADCAST-

chat

  • To disconnect from client side, create a button that would fire the given command on click of it to disconnect the user and the server- socket.disconnect();

To view the full code, visit GitHub- https://github.com/renamsingla/WebSockets

Top comments (0)