DEV Community

Harshit Prasad
Harshit Prasad

Posted on

Socket.io basic setup

Socket.io is a library which is used to establish bidirectional communication between different components of a web application(e.g.- (client ,server), (two different web pages) etc. ). It gives us a simple way to establish such communication in Real-time. This library has a low-latency which makes it real time and ensures almost zero data loss. Following is the basic process of how to establish communication between a client and a server using socket.io in javaScript.

1. Setting up client server address
const io = require('socket.io')(4500);

Enter fullscreen mode Exit fullscreen mode
2. Creating IO communication

io.on('connection', socket =>{
    socket.on('new-user-joined', names => {
        console.log("JOINED THE CHAT",names );
        users[socket.id] = names;
        socket.broadcast.emit('user-joined',names);

    });
Enter fullscreen mode Exit fullscreen mode
socket.emit('new-user-joined',names);

socket.on('user-joined',names =>{
append(`${names} joined the chat`,'right')
})

Enter fullscreen mode Exit fullscreen mode

These two code blocks , server side and client side respectively , gives us a full circuit of communication between client and server.

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

Enter fullscreen mode Exit fullscreen mode

io.on creates and maintains the circuit for communication and listens for requests.

2. socket.emit
socket.emit('new-user-joined',names);
Enter fullscreen mode Exit fullscreen mode

socket.emit emits an event to the opposite party (here - new-user-joined) where the opposite party is waiting to listen to the event to take action. Here, names is a variable passed with the event.

3. socket.on
 socket.on('new-user-joined', names => {

});
Enter fullscreen mode Exit fullscreen mode

socket.on listens to the event emitted by socket.emit with the same name and takes action accordingly.

4. socket.broadcast.emit
 socket.broadcast.emit('user-joined',names);
Enter fullscreen mode Exit fullscreen mode

socket.broadcast.emit emits event as well as data (here - names) to all the clients connected to the server except the user itself. socket.on also listens to the request made be socket.broadcast.emit.

So, here was a simple description and demonstration of how to establish a connection and communication between client and server using socket.io.

Top comments (0)