Tuesday, December 31, 2024

What are WebSockets, and How Does Socket.IO work?

 You're curious enough to search how a thing that you're using is actually working, instead of blindly integrating it into your code, congrats. But really, what is WebSockets, how does it work, and what is socket io precisely?

What are WebSockets?

I suggest you get to know how HTTP servers work before continuing on this topic. Anyways, Websockets are two-way TCP connections that are mainly helped by a long-living HTTP server, It is extremely useful for apps that require real-time interaction and activity like chat apps, notifications, collaborative tools, you name it, it's a wide topic to discover.

Some technique in HTTP was used before WebSockets were invented, one of them was HTTP polling, it's the action of waiting a couple seconds before asking the server if it has new data, this method is obviously ineffective and will waste resources as you go.

Other methods used:

  1. AJAX (Asynchronous JavaScript and XML): This technology allows web applications to make asynchronous requests to the server without reloading the entire page. Google was among the early adopters of AJAX in the mid-2000s, using it for products like Google Suggest, Gmail, and Google Maps.
  2. Comet: This model, made famous by organizations like Google and Meebo, used long-held HTTP connections to push data from the server to the client. Google initially used Comet to add web-based chat to Gmail, while Meebo used it for its web-based chat app.
  3. Long polling: An improvement over regular polling, where the server holds the connection open until new data is available.
  4. Forever frame: This method establishes a long-lived HTTP connection to the server using a hidden frame.
  5. Java applets with LiveConnect: This early solution allowed for server push by creating a long-held connection with the server and communicating with JavaScript on the web page.
Those weren't actually good solutions, instead, they were hacks, and developers needed better solutions to better the user experience, which led to the discovery of WebSockets.

HTTP vs WebSocket

What is Socket.io and how does it implement WebSockets?

Since we now know what a WebSocket is, let's see how Socket.IO implements it. Socket.IO is an extensive abstraction built on top of the WebSocket protocol (which is a low-level protocol). Understanding the difference between Socket.IO and the WebSocket library is important to grasp how they work.

Key Points:

  1. Socket.IO vs WebSocket:

    • WebSocket is a low-level protocol that handles real-time communication but requires manual handling of various tasks like reconnection, fallback, and event handling.
    • Socket.IO is a high-level library built on top of WebSocket, offering features like automatic reconnection, fallback mechanisms, event-driven messaging, rooms, and namespaces.
  2. How Socket.IO Works:

    • Socket.IO uses WebSocket for the actual communication but adds additional layers to handle things like reconnections, message broadcasting, fallback to HTTP polling if WebSocket is unavailable, and much more.
    • When you use WebSocket, you're directly interacting with the protocol and handling all aspects manually. But Socket.IO abstracts away these complexities to give you a more feature-rich, ready-to-use solution for real-time communication.
  3. When to Use Each:

    • If you want full control and don't need additional features, use WebSocket.
    • If you're focused on getting things done quickly and don't want to handle low-level details like reconnections or fallbacks, use Socket.IO.

In short, Socket.IO provides a higher-level, more user-friendly interface built on WebSocket, making it easier to implement real-time applications without having to deal with manual management of WebSocket connections.

Websocket API on the server
const WebSocket = require('ws'); const server = new WebSocket.Server({ port: 8080 }); server.on('connection', (socket) => { socket.on('message', (message) => { console.log('Received:', message); socket.send('Hello Client!'); }); });
Websocket API on the client
const socket = new WebSocket('ws://localhost:8080'); socket.onmessage = (event) => console.log('Message:', event.data); socket.send('Hello Server!');
Socket.io on the server
const io = require('socket.io')(3000); io.on('connection', (socket) => { socket.on('message', (msg) => { console.log('Received:', msg); socket.emit('message', 'Hello Client!'); }); });
Socket.io on the client
const socket = io('http://localhost:3000'); socket.on('message', (msg) => console.log('Message:', msg)); socket.emit('message', 'Hello Server!');


Recent Posts

0 comments:

Post a Comment