Socket IO demo

socket-io-demo

What is Socket.IO? Socket.IO was created in 2010. It was developed to use open connections to facilitate realtime communication, still a relatively new phenomenon at the time. Socket.IO allows bi-directional communication between client and server.

Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server. It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long-polling or automatic reconnection

Now, Socket.IO is a library that provides an abstraction layer on top of WebSockets, making it easier to create realtime applications.

Specifically, Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server.

Thus, we will be using Socket IO library to create real time apps.

Creating a Socket.IO server in Node

ref – https://socket.io/docs/v4/server-initialization/

After we install have installed

in our packpage.json, we can use it in our code. We import it from socket.io and use it to initialize a server to keep track

Now that we have the io Server instance, let’s use it to listen for sockets that connects to it:

We provide an anonymous function (which executes some code) whenever socket connects to our server.

We log to let the user see that a socket has connected. Each socket has a unique id for identification. Each new connection is assigned a random 20-characters identifier

Then we want to provide event actions for when that socket sends this certain event.

Hence, right away, when a socket connects, we say, in the future, if the socket sends an event with string ID
join_room or send_message we want to do some action.

In our case, if the client sends an event join_room, we call join to subscribe the socket to a given channel, where the id is the channel’s unique id.

ref – https://socket.io/docs/v4/broadcasting-events/

You can also broadcast to a room from a given socket:

In the above case, every socket in the room excluding the sender will get the event.

everyone gets the message except the sender

So we run the server and client A.

Client A connects and joins room XMAS, then Client B connects.

Client B joins room XMAS (subscribes to channel XMAS) and then Client A sends message “merry xmas”. Client B will receive it.
Notice Client A will not receive its own message because we have used socket.to(room). We send it to everyone, but excludes the sender.

Everyone including the sender gets the message

Say we simply use emit. It will send the message to everyone AND ALSO the sender.

So let’s open up another browser and join the room XMAS. This time, at Client A’s browser, send a message “HO HO HO”.
You’ll see that everyone, including the sender will get the message.