In my second year of college , Me and my friend used to spend hours on Omegle, chatting with random people from all over the world. It was always a mix of fun and surprise — you never knew who you’d meet next. When Omegle shut down, it left a void. We missed the excitement of those random connections, and that’s when I thought, “Why not build my own version of it?”
In this blog, I’ll break down the process of designing and building such a platform using WebRTC and WebSockets, highlighting the challenges I faced and how I overcame them. By the end of this blog, you’ll not only understand how it works but also have a solid foundation to start building your own real-time communication application
I’m currently working on a project called Noto Chats, which includes this random video chatting feature along with several other exciting functionalities. The system has been thoroughly tested and works seamlessly.
Here’s the Code Link for ramdomvideo chat app https://github.com/Arsh910/RandomVideo-Chat-app
The Tech Stack
Frontend: ReactJS for building an interactive user interface.
Backend: Django Channels for handling WebSocket connections.
Signaling Protocol: WebSockets to establish WebRTC connections.
Media Streaming: WebRTC for peer-to-peer video and audio communication.
Design
Both sides peers will try to make connected , the one that makes first will proceed
Components of the Design:
If you’re not familiar with how WebRTC works, check out this video where I learned from. Here’s a brief overview of the components
1. Client 1 and Client 2
These represent the two users trying to connect. Each client is responsible for creating offers, sending them to the server, and responding to offers they receive.
Analogy: Think of Client 1 and Client 2 as two people who want to have a conversation. They don’t know each other yet but are eager to talk. Each takes the initiative to reach out and wait for the other to respond.
2. Server
The server acts as a matchmaker. It doesn’t handle the actual conversation but facilitates the introduction by passing offers and answers between clients and helping exchange connection details.
Analogy: Imagine a mutual friend introducing two people at a party. The friend doesn’t join their conversation but makes sure they know each other’s names and numbers to start talking.
3. PeerConnection
The PeerConnection is the mechanism that establishes the direct link between the two clients. It manages the exchange of media (audio/video) and ensures the connection remains stable once set up. Like peer1 and peer 2 in above picture .
Analogy: PeerConnection is like a secure, private tunnel between two houses. Once the tunnel is built, the people inside can pass notes, talk, or even send packages without anyone else seeing.
4. ICE Candidates
ICE (Interactive Connectivity Establishment) candidates are the building blocks for the direct connection. These are the routes and network paths that PeerConnection tries to use to establish the best connection.
Analogy: ICE candidates are like maps showing multiple roads to connect two houses. The connection finds the best road (shortest, smoothest) and uses it to ensure a quick and reliable route.
5. Offer and Answer
The connection process starts with one client (Caller) creating an offer and sending it to the other client via the server. The second client (Receiver) creates an answer and sends it back. This exchange sets up the connection.
Analogy: Imagine one person sending a letter saying, “Let’s be friends!” The other person replies, “Sure, I’d like that too!” Once they agree, the friendship begins.
6. Tracks (Audio/Video Streams)
Tracks refer to the media streams (audio and video) that are shared between the clients once the connection is established.
Analogy: Tracks are like live feeds from two cameras and microphones. Each person can see and hear what the other is sharing in real time, like a live video call.
7. Signaling Process
The signaling process involves the exchange of offers, answers, and ICE candidates through the server. This ensures that both clients have the necessary information to establish a direct PeerConnection.
Analogy: The signaling process is like a postal system delivering messages between two people who want to connect. The postman (server) ensures the letters (offers, answers) reach the right recipient so the conversation can begin.
The Dual Role Challenge
To understand the design, it’s important to first grasp a key challenge.
In a traditional phone call, the connection process involves one person acting as the caller and the other as the receiver. However, in a chat app like this, the situation is different. Here, every user is both initiating a connection and waiting for someone else to accept it. This means that everyone must function as both a caller and a receiver simultaneously, creating a system where both roles merge to facilitate seamless.
That’s why I used two peer connections, peer1 and peer2.
Some Important Function:
OnIceCandidateFunc
Handles ICE candidate exchange for establishing a peer-to-peer connection. It Send ICE candidates to the server when Ice candidates are received from STUN Server.
OnTrackFunc
Handles media tracks (audio/video) received from the peer. Activated when a peer transmits tracks. Displays media on the receiver’s interface.
handle_ice
Handles the ice candidates received from other client . It adds the received ice candidates and add them to peer connection.
GetRandomUser
This function selects a random user from a list of online users, excluding the current user. If the list is empty, it throws an error. This ensures a fair random pairing for the chat.
Sendmatch
This function sends a connection request to the server for a selected random user. It constructs a WebSocket message, informing the server of the intent to connect.
Checkmatch
This function verifies if the server’s response confirms a successful match. It checks someone else selected this user. It checks if this user selected the other users. It checks if calling_clicked flag is true (It is important that other user also clicked call).
If all conditions are met, it returns true; otherwise, it returns false. This step ensures the connection is properly validated before proceeding.
Example to Understand the Matching Process
Both sides will send and receive , the side that receives first is taken
Webrtc Connection process
Peer 1 and Peer 2
To establish a connection, two peers, Peer 1 and Peer 2, play distinct roles:
Peer 1: Responsible for creating an offer and receiving an answer.
Peer 2: Handles the offer, generates an answer, and sends it back.
Connection Process
Here’s how the connection process unfolds after a match is made:
1 Initializing Peer 1:
Peer 1 is created on both clients (e.g., Client 1 and Client 2).
Two key events are attached to Peer 1:
OnTrackFunc: Manages incoming audio/video streams from the other peer.
OnIceCandidateFunc: Sends ICE candidates to the server whenever new candidates are received from the STUN server.
2 Creating and Sending the Offer:
Peer 1 generates an offer, which is set as its localDescription.
This offer is sent to the matched user (via the signaling server) by both clients.
3 Handling the Offer with Peer 2:
Upon receiving the offer, Peer 2 is created on both sides.
Similar to Peer 1, Peer 2 is initialized with the OnTrackFunc and OnIceCandidateFunc events.
The received offer is set as Peer 2’s remoteDescription.
4 Generating and Sending the Answer:
Peer 2 generates an answer, which is set as its localDescription.
This answer is sent back to the other client (via the server) by both sides.
5 Completing the Connection:
Once the answer is received, it is set as the remoteDescription of Peer 1.
Both clients now have the required information to establish a direct connection.
Both sides will send and receive
6 Handling ICE Candidates:
As the ICE candidates are exchanged, the OnIceCandidateFunc is triggered.
Received ICE candidates are processed using the handle_ice function, which adds them to the appropriate peer (Peer 1 or Peer 2) based on the connection setup.
7 Setting Up Media Streams:
The OnTrackFunc event is triggered when media tracks (audio/video) are received.
This ensures the remote video and audio streams are displayed on both clients.
Both sides will send and receive
The connection process doesn’t happen simultaneously on both sides due to the randomness of user selection and processing delays. Whichever client completes the setup first becomes the “caller,” while the other acts as the “receiver.”
Once the WebRTC connection is successfully established, both users can enjoy a seamless video chat experience.
Ending the call
Ending a WebRTC call properly is essential to avoid issues during future connections, such as resource leaks or errors while reconnecting. Here’s a detailed guide to properly handle call termination:
1 Remove ICE Candidates:
ICE candidates are used to establish a connection between peers.
Before ending the call, clear any stored ICE candidates to ensure they don’t interfere with future connections.
2 Notify the Other Client:
Inform the other client that the call is ending.
This can be done via the signaling server to gracefully terminate the connection on both sides.
3 Remove Tracks from the Peer Connection:
Remove any media tracks (audio/video) associated with the peer connection to free up resources.
This prevents the continuation of media streams after the call has ended.
4 Reset Call State:
Set the variable calling_clicked to null (or its equivalent in your application).
This ensures that the application knows no active call is ongoing.
Reset Peer 1 and Peer 2 to null.
This releases the memory allocated for peer connections and avoids accidental reuse of old objects.
Set remoteStream to null.
This ensures that the remote audio/video stream is cleared from the application interface.
only one side , as only one of the client initiate the end
Wrapping Up
Building a random video chat app is as exciting as using one! The process comes with its fair share of challenges and learning opportunities, but the satisfaction of seeing your creation come to life is truly rewarding.
As a 3rd-year Computer Science student, I’ve poured my passion and curiosity into this project. While I’ve done my best to ensure everything works seamlessly, there’s always room for improvement. If you notice any flaws or have suggestions to make this project better, please don’t hesitate to reach out to me — I’d love to learn from your insights!
So, grab your keyboard, dive into the code, and who knows — you might just create the next big thing in online communication.
Happy coding! 🎉
Top comments (0)