WebSockets for Kids: A Fun Way to Communicate on the Web

WebSockets for Kids: A Fun Way to Communicate on the Web

Okay, so let us first understand how we communicate with other people. Let’s take an example of you asking questions to your professor.

The Problem with HTTP1

Let’s say you’re at home and you want to ask a particular question to your professor. You ring a call to your professor. The professor picks up your call, and you ask,
“Hey professor, I want you to explain how Earth rotates.”
Your professor answers the question and cuts the call. While you have understood that question, you suddenly get another question.
“Wait, while I understood how Earth rotates, I didn’t understand why Earth is round in the first place.”
You call your professor again. And you keep on doing this. This is much more tedious, right? Every time you forget something, you have to call the professor again. Again, your professor has to pick up the call, and so on and so forth.

This is HTTP1, where you send a request (which in this case is calling your professor and asking a particular question), and the professor gives you a response and cuts the call. That's how HTTP1 works.

Improving with HTTP2

Now, this is a bit annoying, right? So, the next time when you call your professor, what you do here is you keep the call on. You tell the professor:
“I’m going to ask you a bunch of questions, and I want you to answer them one by one.”
So, now you ask the professor the first question. The professor answers your first question. You ask the professor the second question. The professor answers your second question. You ask the professor the third question. The professor answers your third question. Then you cut the call.
Here, you didn’t have to call the professor again and again. This is what HTTP2 is. Here, we have a persistent connection—a connection over the call, in this example—where you ask a question (which is a request), and your professor gives a response. That’s how HTTP 1.1 and 2 work.

Introducing Two-Way Communication with WebSockets

Now, let’s say you call your friend. You call your friend. Your friend picks up your call, and you communicate. You ask questions to your friend. Your friend asks questions to you.

Here, unlike the professor, you don’t have to ask a question, and then your friend answers. Even though you don’t have any question, your friend will say something, and you will say something back. It's a two-way communication. And not a one-way communication like HTTP.

This two-way communication, where if you have something to say, you say it to your friend, and when your friend has something to say, he will say it to you, is called WebSockets.

With WebSockets, you create a connection and you communicate with one another. As shown in the above example, it’s not like the professor where you have to ask a question, and the professor will answer your question only if you’ve asked the question in the first place.

It’s not the case with your friend. You can talk as long as you want, and you can choose to close the connection or cut the call whenever you like. This approach of WebSockets is used everywhere in your life: whether you're texting a friend on WhatsApp, playing a game, designing things on Figma with a friend, or editing a doc with a friend—whenever there’s a need for fast, continuous communication, WebSockets is the way to go.

It's reliable, faster, and great.


Implementing WebSockets

Now that we understand what WebSockets is, how it's used, and where it is applied, let’s look at how to implement it.

Using FastAPI for WebSocket Server

In order to implement WebSockets, we will use FastAPI. FastAPI is a very simple yet efficient and scalable framework to build a server in Python.

FastAPI provides WebSockets directly for us, so we don’t have to do a lot of things. First, we create a friend. We create a function called John. Here, John refers to your friend. Remember, John is a friend, and we are going to interchange the terminology of "friend" and "WebSocket" in the following explanation.

So, whenever you see WebSocket, consider it as a friend.

from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Message text was: {data}")

In this case, John picks up the call (WebSocket accepts the connection). After that, you and John can communicate:

  • John can send data to you using websocket.send_text().

  • You can receive data from John using websocket.receive_text().

Flutter as the WebSocket Client

In the real world, the architecture is mostly client-server, so we need to create a WebSocket client. In this example, we will use Flutter.

WebSocket Client in Flutter

In Flutter, there’s a package called web_socket_channel, which does most of the work for us.

import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;

main() async {
  final wsUrl = Uri.parse('ws://example.com');
  final channel = WebSocketChannel.connect(wsUrl);

  await channel.ready;

  channel.stream.listen((message) {
    channel.sink.add('received!');
    channel.sink.close(status.goingAway);
  });
}

When you have to call a friend, you need their phone number, right? Here, the phone number is the URL of your friend. We can use WebSocket.connect() to pass a URL (similar to a phone number) to establish the connection.

Once the connection is established, you wait until your friend is ready (the WebSocket is connected), and then you can start communicating.

final channel = WebSocketChannel.connect(
  Uri.parse('ws://example.com/socket'),
);

channel.stream.listen((message) {
  print(message);
});

Now, just like your friend keeps talking to you, your WebSocket client listens to the stream of data.

Stream and Sync in WebSockets

Your friend is not only sending one message and then staying quiet. Instead, they keep talking, and you keep listening to their messages over time. This flow of data is called a stream.

In Flutter, the stream is represented by channel.stream.listen(). It's a continuous flow of data that you can keep listening to. To send a message to your friend, you can use channel.sink.add().

channel.sink.add("Hello, friend!");

Think of this like a sync in your home where you wash your hands. Instead of washing your hands, you're washing your messages, and they go to the other side (your friend) through the sync.


Conclusion

This is how you communicate over the web as clients in an architecture using Python and Flutter. Through WebSockets, you can create fast and continuous communication between two parties. It's reliable, fast, and works in real-time, ensuring that you and your friend never run out of things to say.