<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Aritra Roy's blog]]></title><description><![CDATA[Aritra Roy's blog]]></description><link>https://aritra.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 26 Nov 2026 10:59:42 GMT</lastBuildDate><atom:link href="https://aritra.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building a peer to peer video call with WebRTC and WebSockets for beginners (I'm one!)]]></title><description><![CDATA[I started with this project like every other project I start with, on a whim. My beginner-like approach to building web dev applications is flawed and it…]]></description><link>https://aritra.hashnode.dev/building-a-peer-to-peer-video-call-with-webrtc-and-websockets-for-beginners-im-one</link><guid isPermaLink="true">https://aritra.hashnode.dev/building-a-peer-to-peer-video-call-with-webrtc-and-websockets-for-beginners-im-one</guid><category><![CDATA[WebRTC]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><dc:creator><![CDATA[Aritra Roy]]></dc:creator><pubDate>Sat, 29 Jul 2023 21:02:26 GMT</pubDate><content:encoded><![CDATA[<h3 id="heading-the-inception">The inception:</h3>
<p>I started with this project like every other project I start with, on a whim. My beginner-like approach to building web dev applications is flawed and it goes like this.</p>
<ol>
<li><p>Look for a cool tech</p>
</li>
<li><p>Setup a basic boilerplate for it to run on</p>
</li>
<li><p>Start coding it out</p>
</li>
<li><p>Get excited as the thing starts running a bit (Yay!)</p>
</li>
<li><p>Hit a roadblock</p>
</li>
<li><p>Iterate through steps 4-5 a couple of times</p>
</li>
<li><p>Give up (Not so yay :/ )</p>
</li>
</ol>
<p>In spite of the predicaments mentioned above(I know, first-world problems), I ended up making a peer-to-peer WebRTC video call application which runs. I will go through the process so that you are able to do so as well.</p>
<p>*<strong>Note: If you want to do this by yourself the docs can help you out! -</strong> <a target="_blank" href="https://webrtc.org/getting-started/overview">Link to docs</a> *</p>
<h3 id="heading-step-1-play-around-with-media-device-permissions">Step 1: Play around with Media Device permissions</h3>
<p>The browser navigator API gives a lot of options to look into and a video call application will help you get acquainted with that!</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> openMediaDevices = <span class="hljs-keyword">async</span> (constraints) =&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia(constraints);
}

<span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> stream = openMediaDevices({<span class="hljs-string">'video'</span>:<span class="hljs-literal">true</span>,<span class="hljs-string">'audio'</span>:<span class="hljs-literal">true</span>});
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Got MediaStream:'</span>, stream);
} <span class="hljs-keyword">catch</span>(error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error accessing media devices.'</span>, error);
}
</code></pre>
<p>This is the basic setup as given in the first paragraph of the docs which will give you access to the stream of video and audio data from the mentioned camera. Now, you have to feed this stream to a html video element to see it on the screen.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">playVideoFromCamera</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> constraints = {<span class="hljs-string">'video'</span>: <span class="hljs-literal">true</span>, <span class="hljs-string">'audio'</span>: <span class="hljs-literal">true</span>};
        <span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">await</span> navigator.mediaDevices.getUserMedia(constraints);
        <span class="hljs-keyword">const</span> videoElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'video#localVideo'</span>);
        videoElement.srcObject = stream;
    } <span class="hljs-keyword">catch</span>(error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error opening video camera.'</span>, error);
    }
}
</code></pre>
<p>And this code above will start playing the video-audio stream in the video element with the id "local video". That's it, add some styles to the video element and we have a video stream from our device camera running on our screen!</p>
<h3 id="heading-step-2-understanding-how-webrtc-works-on-a-high-level">Step 2: Understanding how WebRTC works on a high level</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690579887502/658896c0-bf78-43c4-91c2-b860fa6fe27c.webp" alt class="image--center mx-auto" /></p>
<p>This is the high-level architecture of how the clients(browsers) communicate over WebRTC.</p>
<p>If we break the image down we can see that,</p>
<ol>
<li><p>There is a server that sits in the middle and exchanges some form of data. We don't know what yet but we do know we are not sending the video and audio stream data through this server. (Spoiler alert: It's called the Signaling server).</p>
</li>
<li><p>The streaming data is sent through this "direct communication" that is mentioned which is what WebRTC is.</p>
</li>
</ol>
<p>So, let's understand what this "signalling server" sitting in the middle does. Its main purpose is to set up the connection between two clients and when everything is finalised, streaming data can start flowing. Let us go into a bit more detail about how this connection is set up.</p>
<h3 id="heading-step-3-setting-up-a-signalling-server-with-socketjs">Step 3: Setting up a signalling server with socket.js</h3>
<p>I would urge you to look a bit into how sockets work and helps clients talk with each other back and forth with the help of a persistent connection. Check out the <a target="_blank" href="https://socket.io/docs/v4/">socket.io docs</a>!</p>
<p>Once you have the server set up, it should look somewhat like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createServer } <span class="hljs-keyword">from</span> <span class="hljs-string">"http"</span>;
<span class="hljs-keyword">import</span> { Server } <span class="hljs-keyword">from</span> <span class="hljs-string">"socket.io"</span>;

<span class="hljs-keyword">const</span> httpServer = createServer();
<span class="hljs-keyword">const</span> io = <span class="hljs-keyword">new</span> Server(httpServer, { <span class="hljs-comment">/* options */</span> });

io.on(<span class="hljs-string">"connection"</span>, <span class="hljs-function">(<span class="hljs-params">socket</span>) =&gt;</span> {
  <span class="hljs-comment">// ...</span>
});

httpServer.listen(<span class="hljs-number">3000</span>);
</code></pre>
<p>Check out how to properly handle incoming messages(using the socket returned in the callback of the <code>io.on("connection", (socket) =&gt; {}</code> ) in the docs and set up CORS as well(in the /*options*/ part of the Server initialization code above).<br />Now, we have to set up a socket listener on the client code as well, for the clients to be able to talk with each other. I used the <a target="_blank" href="https://www.npmjs.com/package/socket.io-client">socket.io-client npm package</a> on my frontend to listen for incoming socket messages.</p>
<p>And once we have a Socket connection ready between the client and the server we can go ahead and setup the webrtc connection between the clients!</p>
<h3 id="heading-step-4-sending-offers-and-answers-over-the-signalling-server">Step 4: Sending offers, and answers over the signalling server</h3>
<p>Now that we have the signalling server set up with the help of WebSockets we can start listening for offers. But what is an offer? An offer is a request created by the RTC peer-connection which basically asks the client that we are trying to connect to if they are ready for connection. But let us create a <strong>peer connection</strong> first :)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> servers = { <span class="hljs-attr">iceServers</span>: [{ <span class="hljs-attr">urls</span>: <span class="hljs-string">"stun:stun.l.google.com:19302"</span> }] };
<span class="hljs-keyword">let</span> peerConnection = <span class="hljs-keyword">new</span> RTCPeerConnection(servers);
</code></pre>
<p>Cool, there we have a peer connection set up. The "servers" variable is a list of servers called ice servers which the WebRTC connections are set over (Remember we have a direct connection and don't connect to an intermediary server for sending streaming data. P.S: In large-scale organisations, they do have their own ice servers to have more granular control over their operations but we are not concerned with that for the time being). This is usually provided by reliable organisations like Google as shown in the above example.</p>
<p>Let us send an offer to the participant we want to connect with. After creating the offer we have to set the local description with the offer. This just means that we are declaring our client as the browser which is sending the offer. And finally, we gotta send the offer!</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">let</span> offer = <span class="hljs-keyword">await</span> peerConnection.createOffer();
 <span class="hljs-keyword">await</span> peerConnection.setLocalDescription(offer); 
 socket.emit(<span class="hljs-string">"chat"</span>, { socketId, offer });
</code></pre>
<p>After we send an offer to our peer we should also be listening for the same on the client. So let us set up a socket listener for the offer on our client.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (message.socketId !== socketId &amp;&amp; message.offer) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"We are getting offer"</span>);
        <span class="hljs-keyword">await</span> peerConnection.setRemoteDescription(
          <span class="hljs-keyword">new</span> RTCSessionDescription(message.offer)
        );
        <span class="hljs-keyword">const</span> answer = <span class="hljs-keyword">await</span> peerConnection.createAnswer();
        <span class="hljs-keyword">await</span> peerConnection.setLocalDescription(answer);
        socket.emit(<span class="hljs-string">"chat"</span>, { socketId, answer });
      }
</code></pre>
<p>In the above code I am looking at the incoming message in the socket listener and seeing if the socketId is the same as the offer sender. This is because the message is going to be retransmitted to all the members in the room in the case of a simple socket emission including the sender itself. And we do not want to set the offer on the offer sender.</p>
<p>On getting the offer successfully on the client we have to set the offer in the remote description. This basically says that the current client is the offer receiver.</p>
<p>After we did that, now's the time to create an answer from the receiving end and set it in the local description before we send it to the other peer.</p>
<p>On receiving the answer in the client(as a socket message) we will need to set the remote description as the answer that is coming through.And this tells us that the other peer is the one that is sending the answer. Let us do that as well!</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">if</span> (message.socketId !== socketId &amp;&amp; message.answer) {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"We are getting answer"</span>);
          <span class="hljs-keyword">const</span> remoteDesc = <span class="hljs-keyword">new</span> RTCSessionDescription(message.answer);
          <span class="hljs-keyword">await</span> peerConnection.setRemoteDescription(remoteDesc);
      }
</code></pre>
<h3 id="heading-step-5-getting-into-ice-candidates">Step 5: Getting into ICE candidates</h3>
<p>On connecting to an ice server a few things happen:</p>
<ul>
<li><p>The client connects to the ice server(Refer to the <strong>server</strong> variable in the peerConnection initialization).</p>
</li>
<li><p>The ice server sends the network information in an object called the <strong>ice candidate</strong> which will be used to relay the network information to our peers.</p>
</li>
<li><p>A list of these ice candidates are sent to the client to tell the plausible ice candidates from best to worst connectivity.</p>
</li>
<li><p>We listen to the incoming candiates from the ice server using the onicecandidate listener on the peerConnection instance.</p>
<pre><code class="lang-javascript">   peerConnection.onicecandidate = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (event.candidate) {
          socket.emit(<span class="hljs-string">"chat"</span>, { socketId, <span class="hljs-attr">iceCandidate</span>: event.candidate });
        }
      };
</code></pre>
</li>
<li><p>On receiving these from the ice servers, the client sends these ICE candidates to the peers through the signalling server as shown in the above code snippet.</p>
</li>
<li><p>Now, we have to listen for incoming socket messages from our peer for the ice candidates.</p>
<pre><code class="lang-javascript">   <span class="hljs-keyword">if</span> (message.socketId !== socketId &amp;&amp; message.iceCandidate) {
          <span class="hljs-keyword">try</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"We are getting ice candidates"</span>);
            peerConnection.addIceCandidate(message.iceCandidate);
          } <span class="hljs-keyword">catch</span> (err) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Error on recieving ice candidate"</span>, err);
          }
        }
</code></pre>
</li>
<li><p>Finally, we have to add the ice candidates on the receiving end of the peer connection using the addIceCandidate method of the peerConnection instance.</p>
</li>
</ul>
<p>Great! We have set up our peer connections on both ends and they have connected with each other properly.</p>
<h3 id="heading-step-5-sending-and-receiving-the-stream">Step 5: Sending and receiving the stream</h3>
<p>The verbose part is done! Now we just have to loop over the tracks of our local stream and send the tracks over the stream. We can do that by calling the getTracks method on the local video element's source object.</p>
<pre><code class="lang-javascript"> localVideoElement.srcObject.getTracks().forEach(<span class="hljs-function">(<span class="hljs-params">track</span>) =&gt;</span> {
      peerConnection.addTrack(track, localVideoElement.srcObject);
    });
</code></pre>
<p>You must have guessed by now that we have to also listen for the incoming stream from our remote peer.</p>
<p>This can easily be done using the ontrack listener method on the peerConnection instance. On getting the streams, we will store that in a media stream array and set it in the remote video element source object. Let's go through the code snippet once.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> remoteStream = <span class="hljs-keyword">new</span> MediaStream();
peerConnection.ontrack = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
      [remoteStream] = event.streams;
      remoteVideoElement.srcObject = remoteStream;
    };
</code></pre>
<p>Make sure to append the above-mentioned remote video element in the DOM and there we go, we have the remote stream running on a video player!</p>
<h3 id="heading-finale-thoughts">Finale thoughts:</h3>
<p>Hope this helped you out somehow in building a peer-to-peer WebRTC video streaming application. My advice would be to play around a bit more with the media devices and see how to manipulate the streams. You can also look into how to connect multiple peers over RTC(More than two). Well, I gotta do that too hehe :P.</p>
<p>Comment and let me know if my doc lacks something. I am wilfully leaving a few common sense things out to help you build this with a bit more self-effort.</p>
<p>Have a great day/night, be happy and healthy :)</p>
]]></content:encoded></item><item><title><![CDATA[Software testing and it's benefits]]></title><description><![CDATA[Learning how testing makes life easier for you and everyone else!]]></description><link>https://aritra.hashnode.dev/software-testing-and-its-benefits</link><guid isPermaLink="true">https://aritra.hashnode.dev/software-testing-and-its-benefits</guid><category><![CDATA[Testing]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Aritra Roy]]></dc:creator><pubDate>Thu, 04 Aug 2022 21:21:40 GMT</pubDate><content:encoded><![CDATA[<p>I remember sneering at the person who told me to write tests for my personal project the first time. It felt so outlandish that I would even need test cases for projects which I can see before my own eyes. So, my notion about tests was that it was for people who didn't manage their code well enough and I self affirmed that I would always write perfect code always (Ah the innocence).</p>
<p>Fast forward a few months, it's the final year of my college and I was able to bag my first ever internship (Woohoo!) and was given a few mini projects which the organisation wanted to get done and it helped me brush up on my skills and learn a bit more too. I digress, but I was still in the bubble that software testing is a waste of time and I would never need anything like this BUT in the immediate next month I got a taste of what a badly tested software does. I had developed a plugin which would be a part of a pretty integral part of the project and the code I was writing at that moment ended up breaking something on another page, which was also written by me! It was pushed to production and fixing that became a hassle. But I hadn't learned my lesson yet and continued to write untested code.</p>
<p>Ironically, I was told to write test cases for the <strong>complete</strong> code base and even though I begrudgingly did it in the beginning of it I ended up finding out how the end to end test cases I was writing saved us huge amounts of time in checking the complete software before pushing it to production. Test your code kids :P. </p>
]]></content:encoded></item></channel></rss>