<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tim Tsai on Medium]]></title>
        <description><![CDATA[Stories by Tim Tsai on Medium]]></description>
        <link>https://medium.com/@Tim_Tsai?source=rss-b94bae44ee81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Uz4l1XJeZR7s5_-SnWw9BQ.jpeg</url>
            <title>Stories by Tim Tsai on Medium</title>
            <link>https://medium.com/@Tim_Tsai?source=rss-b94bae44ee81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:45:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Tim_Tsai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WebSocket | Socket.IO 與它的產地]]></title>
            <link>https://medium.com/@Tim_Tsai/websocket-socket-io-%E8%88%87%E5%AE%83%E7%9A%84%E7%94%A2%E5%9C%B0-7da96930bde9?source=rss-b94bae44ee81------2</link>
            <guid isPermaLink="false">https://medium.com/p/7da96930bde9</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[socketio]]></category>
            <dc:creator><![CDATA[Tim Tsai]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 06:44:35 GMT</pubDate>
            <atom:updated>2022-11-01T08:17:30.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Lo9QHSK91CZNEIrDt5Bx_A.jpeg" /></figure><h4>前言</h4><p>最近 Socket.IO 用比較多，快要忘記它跟他的產地 WebSocket 的差別了，於是決定來好好搞清楚這兩位，順便分享一下我的心得。</p><p>WebSocket 的出現是為了解決 server 難以主動推送訊息的問題，在 server 可能不斷變化的情況下，很難讓 client 即時反應。 WebSocket 實現了 client 和 server 雙邊溝通的可能，讓有著高即時性的網頁可以達到快速反應。</p><p>在 WebSocket 出現之前，也陸續發展出幾種應對方式，但是都有各自的缺點，這裡我們就來討論一下 Polling, Long Polling 到 WebSocket，以及最後建立在 WebSocket 上強化的 Socket.IO。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEwVrBKaNO_Lvlqe1VDZtQ.png" /><figcaption>圖 1 — (左）Polling 固定時間向 Server 詢問 ｜（右）Long Polling 詢問後等待 Server 變化</figcaption></figure><h4>Polling | 輪詢</h4><p>先來討論常聽到的 Polling，簡單來說就是每過一段時間就發送 HTTP request，向 server 詢問有沒有新的資訊，例如每兩秒 Fetch 更新一次。這個技術可以使用在 server 的資料有固定更新頻率的情況下，根據這個頻率從前端發送 HTTP request，可以說是 Polling 比較適合的使用場景。<em>( 圖 1 左)</em></p><p>以一個聊天應用程式來看，Polling 會變得不合適，我們都知道 Polling 是 client 不停地去發送請求，跟 server 要新資料，因此傳出去的訊息如果不是剛好在對方向 server 請求的當下，就要等對方下一次請求才會收到。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM3miTRaJfQ1bhUyXlV7ww.png" /><figcaption>Pollling 模式在聊天軟體可能會錯過新資料</figcaption></figure><p>但是在一般的互動式網頁，無法預期資料什麼時候會更新，因此造成 Polling 不僅耗費資源，要不停的發送 HTTP 請求，也不確定每次都有更新的資料，讓 request 白跑一趟，所以這時聰明的開發者可能會想說，那就等一下 server，看有沒有出現更新，再回覆 response。沒錯，這就是 Polling 的進階版 — Long Polling。</p><h4>Long polling | 長輪詢</h4><p>為了增加每次拿到新資料的機率，發展出了 Polling 的改良版，當 HTTP request 送到 server 後，等待一段時間再回傳，如果期間有發生資料更新，就立刻回傳新資料，這就是所謂的 Long Polling 。<em>( 圖 1 右 )</em></p><p>Long Polling 可以解決 Polling 不斷發送 HTTP request，浪費網路寬頻的問題，透過等待的方式，提高每次請求獲得新資料的效率，但是如果使用 Long Polling 的是一個頻繁更新資料的服務，那 Long Polling 並沒有比較優勢，因為只要收到新資料就會回傳，因此也會形成 HTTP request 不斷來回發送的情況，沒有解決不停發送請求的問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pchtxB3A872ZGCWaKIYYFg.png" /><figcaption>Long Polling 在聊天軟體比 Polling 更高機率即時拿到新資料</figcaption></figure><h4>WebSocket</h4><p>WebSocket 是建立在 TCP 上的通訊<strong>協議</strong>，雖然也是應用層，但跟 HTTP 不同的是，HTTP 是單向溝通的協議，只能由 client 發起，而 WebSocket 則是雙向溝通的協議。</p><p>WebSocket 的連線機制，首先是透過 TCP 三次請求做交握，再透過 HTTP 傳出 Upgrade WebSocket 的請求，通知 server 要換成 WebSocket 協議的方式溝通，server 收到後回傳答覆( acknowledgement )，就完成了 WebSocket 的連線，透過 ws / wss 傳遞訊息。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nzTe5xSfT16wONMyT9el7Q.png" /><figcaption>（左）WebSocket 與 HTTP 都是基於 TCP 上的應用層協議 ｜（右）WebSocket 透過 HTTP 握手後連線</figcaption></figure><p>WebSocket 的實作是透過瀏覽器底層使用 <strong>socket</strong> 作為介面，socket 可以想像是一個介於傳輸層與應用層之間的介面，將 TCP / IP 背後複雜的操作簡單化，方便我們使用 TCP 而不用去考慮 TCP / IP 背後複雜的處。</p><p>WebSocket 可以做到即時雙向的溝通，讓 server 也獲得了話語權 (?)，可以主動推播給 client，這個技術的出現讓高即時性、高互動性獲得了很大的優化，除了 server 主動推送訊息去更新 client 的狀態外，持續的連線也可以大幅減少網路消耗，不用重複傳遞 headers 等資訊，低延遲傳輸也讓現代網站可以提供更好的使用體驗。在傳遞封包時，WebSocket 也幫開發者處理好粘包的問題，不用擔心封包沒有拆分。</p><p>講了那麼多好處， WebSocket 存在一個問題，如果使用者的瀏覽器不支援 WebSocket，那開發者還必須準備一個沒有支援的使用方式。因此，我們的主角 — Socket.IO 就此登場。</p><h4>Socket.IO</h4><p>講完了 Socket.IO 的族譜與演化，總算來到他本人了，接著我們就來看看什麼是 Socket.IO 以及它和 WebSocket 的差別。</p><p>Socket.IO 是一個打包了 WebSocket 的一個 library，它建立於 WebSocket 之上，目的是為了讓使用 WebSocket 的網站在瀏覽器不支援或斷線的情況下，仍然使網站可以運作，而這也是 Socket.IO 強大的地方，他不只幫助開發者處理了很多問題，還提供了各種功能可以使用。</p><p>Socket.IO 提供了 fallback 的機制，在 WebSocket 不支援或斷線的時候，會自動降級成 Long Polling ，確保使用者可以正常使用，同時也提供了 automatic reconnection 的機制，會自動在斷線後嘗試重新連線。另外，使用者傳出封包後斷線，Socket.IO 會 buffer 一段時間，如果有重新連線成功就會幫使用者送出，是不是很貼心？</p><p>除了以上提到的這些，Socket.IO 還有提供 Adapter 方便開發者做 Load Balancer、廣播功能、Namespaces … 等等許多打包好的功能，真的非常方便，讓開發者可以專注在訊息傳遞的部分。</p><h4>結論</h4><p>WebSocket 解決了 client 和 server 雙向溝通的困難，也強化了即時性網頁的使用體驗，同時降低資源消耗，而 Socket.IO 在此基礎之上，再整合成對開發者更友善的工具，真的是個很有意思的技術，推薦給還沒有嘗試過的人，可以跟著 <a href="https://socket.io/get-started/chat">Socket.IO</a> 的官網實作一個聊天室，體驗一下這個有趣的技術。</p><p>這篇純講概念跟比較，讓已經瞭解的人和完全不懂的人可以快速吸收，之後如果有空，再出續集，把使用方法研究一下。</p><h4>參考資料</h4><ul><li><a href="https://ithelp.ithome.com.tw/articles/10193258">webSocket intro. (1/4 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://leesonhsu.blogspot.com/2018/07/socketwebsocketsocketio.html">【筆記】Socket，Websocket，Socket.io的差異</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7da96930bde9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebRTC | One-to-many live stream with ReactJS and Socket.IO — (2) P2P Connection]]></title>
            <link>https://medium.com/@Tim_Tsai/webrtc-one-to-many-live-stream-with-reactjs-and-socket-io-2-p2p-connection-6c126ea1dc9d?source=rss-b94bae44ee81------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c126ea1dc9d</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[live-streaming]]></category>
            <dc:creator><![CDATA[Tim Tsai]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 04:22:53 GMT</pubDate>
            <atom:updated>2022-10-19T04:22:53.511Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebRTC | One-to-many live stream with ReactJS and Socket.IO — (2) P2P Connection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcYbcz4-XFzJWgtAghSnLA.jpeg" /></figure><h4>前言</h4><p>上一篇講到如何透過 MediaStream API 取得影音串流，並且發現在 getDisplayMedia 中，需要透過 getUserMedia 的 audio 取得音訊，才能徵用我們的麥克風，成功達成分享螢幕教學的可能，接下來，我們要試著把我們的影音串流透過與其他人連線，將串流傳出去。</p><h4>WebRTC 怎麼連線 ?</h4><p>在開始連線之前，我們必須先瞭解三個名詞 : ICE, STUN, TRUN。因為這三個技術要說明可能需要再寫另一篇，因此這裡我們先簡單介紹一下 :</p><p><strong>STUN</strong> ( Session Traversal Utilities for NAT ) 的存在簡單來說是為了讓兩個私有網域的 IP 可以知道相互的 Public IP 位置，並且可以穿過 NAT進行溝通。</p><p><strong>TURN</strong> ( Traversal Using Relays around NAT ) 則是負責在 STUN 因為無法穿過 NAT 連線的時候，透過另一個中繼站的 server，轉接兩個用戶之間的溝通資訊。</p><p><strong>ICE</strong> ( Interactive Connectivity Establishment ) 是結合了 STUN 和 TURN 的技術，可以攜帶 STUN 的 candidate 和 TURN 的 candidate，接著判斷中間會不會經過 NAT、有沒有辦法穿透…等，將所有的 candidate 排出優先順序，使用最優先的作為連線使用。在彼此的連線之前，兩個用戶需要提供 ICE 伺服器設定，目的是為每個用戶端提供 ICE 候選對象，然後再將他們互相連線。</p><p>WebRTC 透過交換 SDP ( Session Description Protocol ) 來做連線前的彼此確認，可以使用 HTTP 或 WebSocket 的方式透過 server 交換信令，取得彼此的資訊後就可以進行 peer to peer connection。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oy7ZLwlcielEDRGG5iu0Bg.png" /><figcaption>WebRTC 連線流程</figcaption></figure><p>了解了基本的觀念後，就來實作看看 WebRTC 的連線吧 !</p><h4>第一步 : 建立 RTCPeerConnection</h4><p>剛剛說到 WebRTC 在交換 SDP 前，會先透過 ICE 取得 STUN candidate，透過 RTCPeerConnection 這個 API，將包含 STUN server 的位置的 configuration 傳入，初始化一個的 peerConnection。</p><pre>function initPeerConnection() {<br>  const configuration = {<br>    iceServers: [<br>        {<br>          urls: &#39;stun:stun.l.google.com:19302&#39;,<br>        },<br>      ],<br>    };<br>  const peerConnection = new RTCPeerConnection(configuration);<br>}</pre><h4>第二步 : 連線 WebSocket</h4><p>在發送 SDP 之前，我們要先把 WebSocket 連線好，透過 web server 幫助傳遞信令，同時先監聽回傳的 ice_candidate 和 offer 事件，以及收到事件後將對方的回覆存到 local 的設定裡；收到對方的 offer 並設置好 remote description 後，就可以透過 WebSocket 送出回覆並建立連線。</p><pre>/**<br> * 連線 WebSocket<br> */<br>const [socket, setSocket] = useState({});</pre><pre>function initSocket(){<br>    setSocket(io());<br>}</pre><pre>function socketEvents() {<br>  socket.on(&#39;ice_candidate&#39;, async (data, id) =&gt; {<br>    // 收到 ice_candidate<br>    const candidate = new RTCIceCandidate({<br>    sdpMLineIndex: data.label,<br>    candidate: data.candidate,<br>  });<br>  await PCs[id].addIceCandidate(candidate);<br>});</pre><pre>socket.on(&#39;offer&#39;, async (desc, id) =&gt; {<br>    // 收到 offer<br>    const pc = initPeerConnection();<br>    PCs[id] = pc;<br>    setPeerConnections(PCs);</pre><pre>    // 設定對方的配置<br>    await pc.setRemoteDescription(desc);<br>    <br>    // 發送 answer<br>    await sendSDP(false, pc);<br>  });<br>}</pre><h4>第三步 : 創建並交換信令 SDP ( Session Description Protocol )</h4><p>準備好 PeerConnection 和 WebSocket 後，創建我們用於連線的 SDP ，並透過 WebSocket 送出，與另一個用戶溝通與交換，而對方也會做一樣的事，將我們的資訊儲存後，回覆他的 SDP ，一來一往的確認，最後才能互相連線。</p><pre>async function sendSDP(isOffer, pc) {<br>  if (!pc) {<br>    initPeerConnection();<br>  }</pre><pre>  // 創建 SDP<br>  const localSDP = await pc[<br>    isOffer ? &#39;createOffer&#39; : &#39;createAnswer&#39;<br>  ]({<br>    offerToReceiveAudio: true,<br>    offerToReceiveVideo: true,<br>  });</pre><pre>  // 設定 local SDP<br>  await peerConnection.setLocalDescription(localSDP);</pre><pre>  // 寄出 SDP<br>  const event = isOffer ? &#39;offer&#39; : &#39;answer&#39;;<br>  socket.emit(event, room, pc.localDescription);<br>}</pre><h4>直播方、觀眾或 Server 的程式</h4><p>直播者的程式會多出取得影音串流 getDisplayMedia 的部分，而 WebSocket 的監聽則是被動地去等待 offer 進來 :</p><pre>// 直播者的頁面</pre><pre>function Streamer({<br>  socket, room, localVideo, setIsStreaming,<br>}) {<br>let stream;<br>const PCs = {};<br>const [localStream, setLocalStream] = useState({});<br>const [peerConnections, setPeerConnections] = useState({});</pre><pre>async function createStream() {<br>  const constraints = {<br>    video: {<br>      cursor: &#39;always&#39;,<br>    },<br>    audio: {<br>    autoGainControl: true,<br>      sampleSize: 16,<br>      channelCount: 2,<br>      echoCancellation: true,<br>      noiseSuppression: true,<br>      sampleRate: 44100,<br>    },<br>};</pre><pre>stream = await navigator.mediaDevices.getDisplayMedia(constraints);</pre><pre>const audioStream = await navigator.mediaDevices.getUserMedia(<br>{ audio: true },<br>).catch((err) =&gt; { console.log(err); });<br>    const [audioTrack] = audioStream.getAudioTracks();<br>    stream.addTrack(audioTrack);<br>    setLocalStream(stream);<br>    localVideo.current.srcObject = stream;<br>  }</pre><pre>function initPeerConnection() {<br>  const configuration = {<br>   iceServers: [<br>      {<br>        urls: &#39;stun:stun.l.google.com:19302&#39;,<br>      },<br>    ],<br>  };<br>const peerConn = new RTCPeerConnection(configuration);</pre><pre>// 增加本地串流<br>stream.getTracks().forEach((track) =&gt; {<br>  peerConn.addTrack(track, stream);<br>});</pre><pre>// 找尋到 ICE 候選位置後，送去 Server 與另一位配對<br>peerConn.onicecandidate = (e) =&gt; {<br>  if (e.candidate) {<br>  // 發送 ICE<br>    socket.emit(&#39;ice_candidate&#39;, room, {<br>      label: e.candidate.sdpMLineIndex,<br>      id: e.candidate.sdpMid,<br>      candidate: e.candidate.candidate,<br>    });<br>  }<br>};</pre><pre>async function sendSDP(isOffer, pc) {<br>  if (!pc) {<br>    initPeerConnection();<br>  }</pre><pre>  // 創建SDP信令</pre><pre>  const localSDP = await pc[isOffer ? &#39;createOffer&#39; : &#39;createAnswer&#39;]({<br>    offerToReceiveAudio: true, // 是否傳送聲音流給對方<br>    offerToReceiveVideo: true, // 是否傳送影像流給對方<br>});</pre><pre>  // 設定本地SDP信令</pre><pre>  await pc.setLocalDescription(localSDP);</pre><pre>  // 寄出SDP信令<br>  const event = isOffer ? &#39;offer&#39; : &#39;answer&#39;;<br>  socket.emit(event, room, pc.localDescription);<br>}</pre><pre>function connectIO() {<br>  socket.on(&#39;ice_candidate&#39;, async (data, id) =&gt; {<br>    // 收到 ice_candidate;<br>    const candidate = new RTCIceCandidate({<br>      sdpMLineIndex: data.label,<br>      candidate: data.candidate,<br>    });<br>    await PCs[id].addIceCandidate(candidate);<br>  });</pre><pre>  socket.on(&#39;offer&#39;, async (desc, id) =&gt; {<br>    // 收到 offer;<br>    const pc = initPeerConnection();<br>    PCs[id] = pc;<br>    setPeerConnections(PCs);</pre><pre>    // 設定對方的配置<br>    await pc.setRemoteDescription(desc);</pre><pre>    // 發送 answer<br>    await sendSDP(false, pc);<br>  });</pre><pre>  setIsConnected(true);<br>}</pre><pre>const init = () =&gt; {<br>  createStream();<br>  connectIO();<br>};</pre><pre>return (<br>  &lt;section id=&quot;streamer-video&quot;&gt;<br>    &lt;video<br>      ref={localVideo}<br>      muted<br>      autoPlay<br>      playsInline<br>      controls<br>    &gt;<br>      Your browser does not support the video tag.<br>    &lt;/video&gt;</pre><pre>    &lt;Button <br>      variant=&quot;contained&quot; <br>      type=&quot;button&quot;<br>      onClick={init}<br>    &gt;<br>      Share Screen<br>    &lt;/Button&gt;<br> &lt;/section&gt;<br> );<br>}</pre><p>觀眾的程式會主動去申請連線，因此在 RTCPeerConnection 會多設定一些內容（ 決定是否要傳影音過去），在 WebSocket 的部分則是主動送出 offer ，並等待直播方的 answer :</p><pre>// 觀眾或學生的頁面</pre><pre>function Video({<br>socket, isConnect, setIsConnect, room,<br>}) {<br>let peerConnection;<br>const navigate = useNavigate();<br>const [userData, setUserData] = useState(&#39;&#39;);<br>const localVideo = useRef();</pre><pre>function connectIO() {<br>  socket.on(&#39;answer&#39;, async (desc) =&gt; {<br>  // 收到 answer<br>  // 設定對方的配置<br>    await peerConnection.setRemoteDescription(desc);<br>  });</pre><pre>socket.on(&#39;ice_candidate&#39;, async (data) =&gt; {<br>  // 收到 ice_candidate<br>  const candidate = new RTCIceCandidate({<br>    sdpMLineIndex: data.label,<br>    candidate: data.candidate,<br>  });</pre><pre>    await peerConnection.addIceCandidate(candidate);</pre><pre>  });<br>}</pre><pre><br>function initPeerConnection() {<br>  const configuration = {<br>    iceServers: [<br>      {<br>      urls: &#39;stun:stun.l.google.com:19302&#39;,<br>      },<br>    ],<br>  };</pre><pre>peerConnection = new RTCPeerConnection(configuration);<br>peerConnection.addTransceiver(&#39;video&#39;, { direction: &#39;recvonly&#39; })<br>peerConnection.addTransceiver(&#39;audio&#39;, { direction: &#39;recvonly&#39; });</pre><pre>// 找尋到 ICE 候選位置後，送去 Server 與另一位配對<br>peerConnection.onicecandidate = (e) =&gt; {<br>  if (e.candidate) {<br>   // 發送 ICE<br>    socket.emit(&#39;ice_candidate&#39;, room, {<br>      label: e.candidate.sdpMLineIndex,<br>      id: e.candidate.sdpMid,<br>      candidate: e.candidate.candidate,<br>    });<br>  }<br>};</pre><pre>// 監聽 ICE 連接狀態<br>peerConnection.oniceconnectionstatechange = (e) =&gt; {<br>  if (e.target.iceConnectionState === &#39;disconnected&#39;) {<br>    localVideo.current.srcObject = null;<br>  }<br>};</pre><pre>// 監聽是否有流傳入，如果有的話就顯示影像<br>peerConnection.ontrack = (data) =&gt; {<br>    // 接收流並顯示遠端視訊<br>    localVideo.current.srcObject = data.streams[0];<br>  };<br>}</pre><pre>async function sendSDP(isOffer) {<br>  if (!peerConnection) {<br>  initPeerConnection();<br>}</pre><pre>// 創建SDP信令<br>const localSDP = await peerConnection.createOffer();</pre><pre>// 設定本地SDP信令<br>await peerConnection.setLocalDescription(localSDP);</pre><pre>// 寄出SDP信令<br>const event = isOffer ? &#39;offer&#39; : &#39;answer&#39;;<br>  socket.emit(event, room, peerConnection.localDescription);<br>}</pre><pre>const connect = async () =&gt; {<br>  await initPeerConnection();<br>  await connectIO();<br>  await sendSDP(true);<br>  await setIsConnect(true);<br>};</pre><pre>useEffect(() =&gt; {<br>  socket.emit(&#39;join&#39;, room);<br>}, [socket]);</pre><pre>return (<br>    &lt;section id=&quot;video-container&quot;&gt;<br>     &lt;video<br>        ref={localVideo}<br>        autoPlay<br>        playsInline<br>        controls<br>      &gt;<br>        Your browser does not support the video tag.<br>      &lt;/video&gt;</pre><pre>      &lt;Button<br>        type=&quot;button&quot;<br>        onClick={connect}<br>      &gt;<br>        connect<br>      &lt;/Button&gt;<br>    &lt;/section&gt;<br>  );<br>}</pre><p>Server 負責的事情是將以上傳遞的資訊傳給正確的人 :</p><pre>// Server 的 socket.io 事件</pre><pre>io.on(&#39;connection&#39;, (socket) =&gt; {<br>  // Join Room<br>  socket.on(&#39;join&#39;, (room) =&gt; {<br>    socket.join(room);<br>    socket.to(room).emit(&#39;viewer&#39;, socket.id);<br>  });</pre><pre>  // Transport Offer<br>  socket.on(&#39;offer&#39;, (room, desc) =&gt; {<br>    socket.to(room).emit(&#39;offer&#39;, desc, socket.id);<br>  });</pre><pre>  // Transport Answer<br>  socket.on(&#39;answer&#39;, (room, desc) =&gt; {<br>    socket.to(room).emit(&#39;answer&#39;, desc);<br>  });</pre><pre>  // Exchange ice candidate<br>  socket.on(&#39;ice_candidate&#39;, (room, data) =&gt; {<br>    socket.to(room).emit(&#39;ice_candidate&#39;, data, socket.id);<br>    socket.to(room).emit(&#39;test&#39;, data, socket.id);<br>    });<br>  });</pre><p>理解了怎麼透過 ICE 和 SDP 達到確認位置與穿透 NAT 後，就可以透過 Socket.IO 與 web server 傳遞信令，互相連線啦 !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2aEXgnr0l0zZBdCuMq6dWg.gif" /><figcaption>WebRTC 成功連線 ｜（左）觀眾 ｜（右）直播者</figcaption></figure><h4>結論</h4><p>實際上在我的專案中程式會複雜很多，以上的程式是單純抽取出連線的部分，如果想要了解更詳細的內容的話，可以到 <a href="https://webrtc.org/getting-started/peer-connections">WebRTC</a> 或者我的 <a href="https://github.com/tyt-timtsai/Wolfon">Github</a> 看 source code，除了連線影音串流外，還有錄影跟上傳到雲端的功能，未來也會陸續寫成文章記錄起來</p><h4>參考資料</h4><ul><li><a href="https://webrtc.org/getting-started/peer-connections">Getting started with peer connections | WebRTC</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10209725">30-29之 WebRTC 的 P2P 打洞術 ( ICE ) - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c126ea1dc9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebRTC | One-to-many live stream with ReactJS and Socket.IO — (1) getDisplayMedia & getUserMedia]]></title>
            <link>https://medium.com/@Tim_Tsai/webrtc-one-to-many-live-stream-with-reactjs-and-socket-io-1-getdisplaymedia-getusermedia-43df2116a959?source=rss-b94bae44ee81------2</link>
            <guid isPermaLink="false">https://medium.com/p/43df2116a959</guid>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Tim Tsai]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 14:41:25 GMT</pubDate>
            <atom:updated>2022-10-18T14:41:25.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>WebRTC | One-to-many live stream with ReactJS and Socket.IO — (1) getDisplayMedia &amp; getUserMedia</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lcYbcz4-XFzJWgtAghSnLA.jpeg" /></figure><h4>前言</h4><p>我在 AppWorks School 的個人專案是做直播學程式的社群網站，所以除了之前提到的 Code Sandbox 之外，當然還有一個主題 — 直播。</p><p>我學程式之後常常在想，網路上那麼多教學程式語言的影片和線上課程，但相較之下，比較少 terminal 指令、git 指令、 docker 、AWS 怎麼使用等等的教學。</p><blockquote>程式不會照著你想的執行，而是照著你寫的執行。</blockquote><p>程式語言的教學相對簡單，程式怎麼寫，就會怎麼跑，沒有太多例外。但是指令、環境等等的工具，卻跟使用者的電腦設定、前後步驟…等，太多可能會影響到執行結果的因素了，所以如果要教學相關的知識，必須要透過直播與聊天室做到雙向溝通，甚至學生執行時出了問題，要可以上傳自己的截圖給老師，讓老師現場 review，才可以達到好的教學跟學習效果。</p><p>回到正題，要讓老師可以快速跟同學互動的直播想必需要是低延遲的直播，學習程式也需要好的畫面品質，而這種互動式學習大多也在 30 人以下，於是我選擇使用 WebRTC，建立一個想像中的直播學習平台。</p><h4>什麼是 WebRTC ?</h4><p><a href="https://webrtc.org/">WebRTC</a> 是網頁即時通訊 ( Web Real-Time Communication ) 的縮寫，透過 RTCPeerConnection API 和 MediaStream API 組合而成的技術，讓瀏覽器可以不透過其他工具或 plugin 就可以進行點對點的影音連線，在 2010 年被 Google 收購，後來成為開源，也被 W3C 納入成為推薦標準，也就是成熟而且可以廣泛使用的技術。</p><h4>取得影音串流 — getDisplayMedia / getUserMedia</h4><p>首先，要開發直播功能，第一步就是先建立自己的影音串流，才可以把影音傳遞出去。WebRTC 提供的 MediaStream API 中，有兩個主要用來取得影音串流的 API — getDisplayMedia 和 getUserMedia ，透過瀏覽器 navigator 的 mediaDevices 取得螢幕或瀏覽器畫面，以及相機鏡頭。</p><p>getDisplayMedia 和 getUserMedia 都要傳入 constraints 設定影像和音訊，除了改成 true 之外，還有更細節得設定，詳細可以參考 <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#parameters">MDN</a> ，以下是用React JS 取得影音串流的程式 :</p><pre>async function LiveStream(){<br>  const localVideo = useRef();<br>  const [localStream, setLocalStream] = useState({});<br>  async function createStream() { <br>    const constraints = { <br>      video:true,<br>      audio: true,<br>    };</pre><pre>     // 使用 getDisplayMedia 取得螢幕畫面<br>     stream = await navigator.mediaDevices.getDisplayMedia(<br>         constraints<br>     );<br>   }</pre><pre>  return (<br>    &lt;&gt;<br>     &lt;video<br>        ref={localVideo}<br>        height=&quot;auto&quot;<br>        id=&quot;localVideo&quot;<br>        muted<br>        autoPlay<br>        playsInline<br>        controls<br>      &gt;<br>         Your browser does not support the video tag.<br>      &lt;/video&gt;<br>      &lt;button<br>       type=&quot;button&quot;<br>       onClick={createStream}<br>      &gt;<br>        分享螢幕 Share Screen<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>   )<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMiAm9MgYWvxKLmwK-OXjQ.gif" /><figcaption>getDisplayMedia 取得螢幕與瀏覽器畫面分享</figcaption></figure><pre>async function LiveStream(){<br>  const localVideo = useRef();<br>  const [localStream, setLocalStream] = useState({});<br>  async function createStream() { <br>    const constraints = { <br>      video:true,<br>      audio: true,<br>    };</pre><pre>     // 使用 getUserMedia 取得相機畫面<br>     stream = await navigator.mediaDevices.getUserMedia(<br>         constraints<br>     );<br>   }</pre><pre>  return (<br>    &lt;&gt;<br>     &lt;video<br>        ref={localVideo}<br>        height=&quot;auto&quot;<br>        id=&quot;localVideo&quot;<br>        muted<br>        autoPlay<br>        playsInline<br>        controls<br>      &gt;<br>         Your browser does not support the video tag.<br>      &lt;/video&gt;<br>      &lt;button<br>       type=&quot;button&quot;<br>       onClick={createStream}<br>      &gt;<br>        分享螢幕 Share Screen<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>   )<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wjuQCZPoS8b3P8qfxfpqTA.gif" /><figcaption>getUserMedia 取得相機畫面</figcaption></figure><h4>getDisplayMedia 的聲音呢 ?</h4><p>實作以上的程式會發現，getDisplayMedia 錄不到我們說話的聲音，這是因為 getDisplayMedia 的 audio 只會取得電腦放出來的聲音，必須透過 getUserMedia 取得 audio 才能收錄我們麥克風的聲音，透過 addTrack 的方法將音訊加影像串流，就可以成功達到影音串流了。</p><pre>async function LiveStream(){<br>  const localVideo = useRef();<br>  const [localStream, setLocalStream] = useState({});<br>  async function createStream() { <br>    const constraints = { <br>      video:true,<br>      audio: true,<br>    };</pre><pre>     stream = await navigator.mediaDevices.getDisplayMedia(<br>         constraints<br>     );</pre><pre>     // 取得麥克風的音訊<br>     const audioStream = await <br>         navigator.mediaDevices.getUserMedia({audio: true})<br>         .catch((err) =&gt; { console.log(err)});</pre><pre>     const [audioTrack] = audioStream.getAudioTracks();    </pre><pre>     // 將音訊加入串流     <br>     stream.addTrack(audioTrack);<br>     setLocalStream(stream);<br>     localVideo.current.srcObject = stream;<br>   }</pre><pre>  return (<br>    &lt;&gt;<br>     &lt;video<br>        ref={localVideo}<br>        height=&quot;auto&quot;<br>        id=&quot;localVideo&quot;<br>        muted<br>        autoPlay<br>        playsInline<br>        controls<br>      &gt;<br>         Your browser does not support the video tag.<br>      &lt;/video&gt;<br>      &lt;button<br>       type=&quot;button&quot;<br>       onClick={createStream}<br>      &gt;<br>        分享螢幕 Share Screen<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>   )<br> }</pre><p>將取得的影音串流設為 video tag 的 srcObject，便可以透過 HTML 播放及時的影音畫面，到這裡就完成了直播的第一步 : 取得影音串流。</p><h4>結論</h4><p>WebRTC 因為有 MediaStream API，取得畫面是相對簡單的一件事，只要直接使用瀏覽器提供的 API 就可以很快速的取得影音，加上 HTML 的 video，就可以馬上看到自己直播的畫面啦。接下來要解決的問題是，怎麼跟其他的使用者連線並傳遞我們的影音串流，這就是 WebRTC 要解決的另一件事，所謂的 P2P ( peer to peer ) Connection 背後的運作。</p><p>這是我第一次挑戰直播串流相關的專案，使用 WebRTC 並試著去理解它的運作原理後，覺得非常有趣，在我們使用通訊軟體、會議程式的背後，是個由各種強大的技術組合而成的模式，經過數個溝通程序以及穿透，才達到低延遲和高品質的視訊！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43df2116a959" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker | 用 Dockerfile 與 Node.js 實作簡易 CodeSandbox 後端 — part 2]]></title>
            <link>https://medium.com/@Tim_Tsai/docker-%E7%94%A8-dockerfile-%E8%88%87-node-js-%E5%AF%A6%E4%BD%9C%E7%B0%A1%E6%98%93-codesandbox-%E5%BE%8C%E7%AB%AF-part-2-d55c99708eb8?source=rss-b94bae44ee81------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55c99708eb8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[codesandbox]]></category>
            <category><![CDATA[exception-handling]]></category>
            <dc:creator><![CDATA[Tim Tsai]]></dc:creator>
            <pubDate>Tue, 11 Oct 2022 10:28:20 GMT</pubDate>
            <atom:updated>2022-10-12T08:09:11.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker | 用 Dockerfile 與 Node.js 實作簡易 CodeSandbox 後端 — part 2</h3><h4>前言</h4><p>收尾專案時，發現要整理的東西太多了，不如就來寫第二篇分享吧 !? ( 一種不想面對正事時，就開始整理房間的概念… )</p><p>上一篇說到，可以運作 code sandbox 之後，緊接著就會面臨到各種無情的攻擊，身邊的工程師們就會想在這上面試試看 while true, setInterval 無限循環，如果你也實作 code sandbox，而且身邊也有一堆對擊垮你 server 有著濃厚興趣的工程師朋友們，這篇就是為你寫的。</p><h4>Infinite Loop</h4><p>無限迴圈，顧名思義是一個不停運作的迴圈，在遭到強制停止前，會持續運行下去，會吃掉很多 CPU 效能。雖然也有用得上它的時候，但在正常情況下，Infinite Loop 的出現，是帶著風險的。</p><p>試想一下，我們剛做完正在試用的 code sandbox 收到 Infinite Loop 的程式後，整個 route 就在等這份程式回覆，下一位使用著的程式也在等前一份程式，再下一位、下下一位使用者就開始了無窮排隊…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1W-lmQ2n7_u-Qmu0eeNGMQ.png" /></figure><p>在這個狀況下，若是 code sandbox 沒有處理這個問題就上線，那麼一行簡單的 while true，就可以讓你的 server 說再見。</p><p>這麼嚴重的問題要怎麼解決呢 ？ 分成兩個層面 : <strong>限制資源</strong>與<strong>終止程式。</strong></p><h4>監測 Container 的資源</h4><p>首先，先來了解怎麼監測 container 使用了多少資源，透過 docker stats 的指令，取得 container 的 CPU 使用率、 Memory 用量， I/O … 等數據。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPgAk6eGTYbqMmyh9-XS2g.png" /><figcaption>docker stats 監測 container 的資源使用</figcaption></figure><p>從上面的數據可以發現，一個執行 while true 的 container 在 CPU 的使用上會直接達到接近 100%，如果今天 server 架在 EC2 的單核機器上，那可能就撐不住下一個 Infinite Loop 了。</p><p>Memory 也是一樣，若今天一個 container 可以無上限的佔用 server 的記憶體，在記憶體較小的機台可能很快就會發生 OOM 的問題。</p><p>為了避免以上的狀況，我們可以透過指令來限制一個 container 能用多少 CPU 和 Memory 的資源。</p><h4>限制 Container 的使用資源</h4><p><strong>CPU 的限制</strong>可以透過 Docker 指令參數 — — cpus 去設定，或者用 cpu-period 加上 cpu-quota 去限制固定時間內的使用次數，可以做到更彈性的設定。</p><p><strong>Memory 的限制</strong>是透過 — — memory 的指令設定最大的記憶體用量，另外可以用 — — memory-swap 限制記憶體交換量。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*noIsPMPl-ee_ACgE6KIziw.png" /><figcaption>透過 CPU 限制的方式 ( 限制最高每秒使用單個 CPU 的 25% )</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJ7PU6fg2z6M50oN_3B3_A.png" /><figcaption>透過 Memory 限制的方式 ( 最小為 6m )</figcaption></figure><p>透過這些指令來限制 container，我們再次去 docker stats 看看跑起來的 container 後，可以發現資源真的被控制在我們設定的資源用量下，再多起幾個 Infinite Loop 的程式也都撐得住。</p><pre>const { stdout } = await exec(<br>  `docker run \<br>  --name ${id} \<br>  --cpus=&quot;0.05&quot; \<br>  --memory 7m \<br>  --memory-swap=0 \<br>  -v $(pwd):/code \<br>  --rm runtime-python`<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGG3QPgDPFn64UZcdTvmrA.png" /><figcaption>CPU 被限制在 5% 上下，Memory limit 是設定的 7 MB</figcaption></figure><p>到這裡我們已經可以控制 container 的資源了，可以避免一行指令就 server crash 的慘劇，但是依然還沒解決 Infinite Loop 持續運作的問題，數量一多，server 一樣要過勞，所以接下來就來看看如何停止它的運作。</p><h4>如何控制 Infinity Loop 終止</h4><p>停止 Container 跟控制資源一樣可以分成兩個面向來看 : CPU 跟 Memory。</p><p><strong>Memory<br></strong>在 docker inspect 顯示當中，可以看到在 State 欄位底下有一個 OOMKilled 的屬性，我們可以在啟動時打開這個屬性，或是只要有設定 Memory limit 的情境下，container 就會因為超過可以使用的 Memory 而被終止。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-IrLYTxKURIp9Iq7nOWfjw.png" /><figcaption>執行 docker inspect 得到的內容</figcaption></figure><p>因此簡單來說，透過指令啟動 container 時，只要加上 — — memory 的設定，就可以針對會吃很多記憶體空間的程式監測並終止。</p><p><strong>CPU<br></strong>相較於 Memory，針對 CPU 沒有類似 OOMkilled 的屬性，也不會在超過 cpu limit 時 kill container，所以針對 CPU 的問題，我目前是透過限制執行時間來控制，如果超時就執行 docker kill，以此來處理 Infinite Loop 程式不會終止的問題。</p><p>我的做法是，在執行 docker run 之前，先 setTimeout 準備 docker kill，如果執行時間超過時，就會自動 kill container；而正常執行時，則要在執行結束後 clearTimeout，將原本的 setTimeout 刪除，這樣就可以透過自訂的運行時間，來達到一定程度的控制。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uggD6RH6ZETlnrY96eT_bw.png" /><figcaption>setTimeout 用來控制 container 終止</figcaption></figure><p>結合上一篇的程式 :</p><pre>const fs = require(&#39;fs&#39;);<br>const fsPromises = fs.promises;<br>const util = require(&#39;util&#39;);<br>const exec = util.promisify(require(&#39;child_process&#39;).exec);<br>let EXECUTION_TIME = 6000;</pre><pre>async function writeFile(code){<br>  await fsPromises.writeFile(`./code.py`, code);<br>}</pre><pre>async function compile(id, code){<br>  let result = null;</pre><pre>  const inspect = setTimeout(async () =&gt; {<br>    await exec(`docker kill ${id}`);<br>    return &#39;Execute Over Time.&#39;;<br>  }, EXECUTION_TIME);</pre><pre>  try{<br>    await writeFile(code);    const { stdout } = await exec(<br>      `docker run \<br>      --name ${id} \<br>      -v $(pwd):/code \<br>      --rm runtime-python`,<br>    );    <br>    return stdout;<br>  } catch (error){<br>    const { stdout, stderr } = error;<br>    return { stdout, stderr };    <br>  } finally {<br>    await fsPromises.rm(&#39;./code.py&#39;);<br>    clearTimeout(inspect);<br>  }<br>}</pre><h4>結論</h4><p>開發到這裡，已經可以正常的運行程式，也可以抵禦工程師朋友們的各種程式攻擊，但是目前針對 CPU 我還沒找到自動終止的方法，只能先透過 setTimeout 透過時間來控制 container，如果有找到更好的方法，也歡迎留言交流一下。</p><p>最近依舊在收尾階段，覺得寫文章蠻放鬆的，也因為開始些文章後，會自然而然的回顧專案中用到的各種技術以及開發出的功能，發現有些東西好像值得紀錄一下，預計接下來再陸續寫出來分享。</p><h4>參考資料</h4><ul><li><a href="https://hoohoo.top/blog/docker-resource-memory-and-cpu-setting/">Docker 的 Memory 與 CPU 資源管理</a></li><li><a href="https://koding.work/how-to-use-docker-cpu-resource-limit/">一次搞懂 Docker CPU 資源限制 - 叩頂窩客</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10194839">Day 27：Docker Container 資源限制 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55c99708eb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker | 用 Dockerfile 與 Node.js 實作簡易 CodeSandbox 後端]]></title>
            <link>https://medium.com/@Tim_Tsai/docker-%E7%94%A8-dockerfile-%E8%88%87-node-js-%E5%AF%A6%E4%BD%9C%E7%B0%A1%E6%98%93-codesandbox-%E5%BE%8C%E7%AB%AF-3673b7e6ea06?source=rss-b94bae44ee81------2</link>
            <guid isPermaLink="false">https://medium.com/p/3673b7e6ea06</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[codesandbox]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Tim Tsai]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 03:52:44 GMT</pubDate>
            <atom:updated>2022-10-18T05:46:16.045Z</atom:updated>
            <content:encoded><![CDATA[<h4>前言</h4><p>最近在收尾自己在 AppWorks School 的個人專案，是一個直播學程式的社群網站，有個功能是線上程式編輯器，為了達到可以邊看直播邊實作的體驗，要讓程式可以真的運行，並可以拿到執行結果。</p><p>趁著收尾的時間，分享也紀錄一下我實作的 code sandbox，支援 javascript / python / golang 三種語言。</p><h4>CodeSandbox</h4><p><a href="https://codesandbox.io/s/">CodeSandbox</a> 是一個非常強大的線上開發環境，簡單來說，就是一個提供各種語言環境，讓你可以在線上寫多種不同語言的開發與測試。</p><figure><img alt="CodeSandbox 選擇語言介面" src="https://cdn-images-1.medium.com/max/1024/1*gYzCAqyw3jeJxpPMmTaGHg.png" /><figcaption>CodeSandbox 環境介面</figcaption></figure><p>為了達到相似的體驗，我在自己的專案中開發了一個小型 CodeSandbox :</p><figure><img alt="Code sandbox 運行 JavaScript 程式" src="https://cdn-images-1.medium.com/max/1024/1*lPgXaWEUPDxSCrbgc01SgQ.png" /><figcaption>專案中用 JavaScript for 迴圈執行twoSum 的程式</figcaption></figure><p>前端的部分用 <a href="https://ace.c9.io/">React-Ace Editor</a> 來做編輯器，它提供很多語言的提示字，可以讓寫程式方便很多，因為主要講後端，這部分就留到下次再來寫 🤣。</p><p><strong>後端主要的挑戰是，當 code 送到後端時，要怎麼運行這份程式，又要怎麼拿到運行的結果 ?</strong></p><figure><img alt="Code sandbox 後端流程架構" src="https://cdn-images-1.medium.com/max/1024/1*otFjB4bMnuhP69FfB5p42Q.png" /><figcaption>Code sandbox 後端流程架構</figcaption></figure><h4>第一步：寫檔</h4><p>首先，要怎麼在運行中的程式裡運行另一個其他語言的程式 🤔 ? 我的想法是 : 跟原本的程式一樣，再寫成一個檔案，然後執行。</p><pre>const fs = require(&#39;fs&#39;);<br>const fsPromises = fs.promises;</pre><pre>async function writeFile(code){<br>  await fsPromises.writeFile(`./code.py`, code);<br>}</pre><p>透過 node 提供的 fs module，可以做實體檔案的新增與修改，根據不同的語言，我們要建立成不同的副檔名，像是 .js .py .go …等，再將前端送過來的 code 寫進去，這裡先以 Python 舉例的話，我們就準備好可以執行的檔案 code.py 了。</p><h4>第二步：準備環境</h4><p>準備好可以運行的程式，接下來當然不可能要自己手動輸入指令，去安裝 python 的環境，然後手動執行吧 ? 這時就可以利用 Dockerfile 的各種好處來幫我們做事！</p><p>FROM 指定 python 的環境，通常使用 alpine 的版本比較輕量，WORKDIR 指定進入時的位置後，最後透過 CMD 執行程式，簡單的三行就可以達到 sandbox 需要的功能，接下來只要運行這個 Dockerfile 生成的 image，就可以進到需要的環境，並自動執行程式。</p><pre># 以 python 為例<br>FROM python:3.11.0rc1-alpine3.16</pre><pre>WORKDIR /code</pre><pre>CMD [&quot;python3&quot;, &quot;code.py&quot;]<br></pre><pre># 如果是 node.js<br>FROM node:16.17-alpine3.15</pre><pre>WORKDIR /code</pre><pre>CMD [&quot;node&quot;, &quot;code.js&quot;]</pre><p>準備好 Dockerfile 之後，先透過指令生成 image ：</p><pre>docker build Dockerfile . -t runtime-python</pre><p>到這裡就準備好所有需要的檔案與環境了，接著就可以試著把程式丟進 container 運行了。</p><h4>第三步：運行</h4><p>到這一步又面臨另一個難題，要怎麼在 node 程式中執行 terminal 指令？ 肯定需要找個人來幫忙執行指令，這個人就是 node 的 child_process ！</p><p>透過 child_process 裡 exec 的方法，可以在 node 程式執行 terminal 指令，有了這個好朋友的幫忙，就可以實現在 node 中執行 docker run 了，是不是很好用？</p><pre>const util = require(&#39;util&#39;);<br>const exec = util.promisify(require(&#39;child_process&#39;).exec);</pre><pre>async function compile(id){<br>  await exec(<br>  `docker run \<br>  --name ${id} \<br>  -v $(pwd):/code \<br>  --rm runtime-python`,<br>  );<br>}</pre><p>執行 docker run 時，有幾個地方需要特別設定，-v 也就是指定 docker 掛上 volumn，這個設定可以把我們準備好的 code.py 掛進去 container 內，才能執行這個檔案；- -rm 是讓 container 運行結束時自動 kill，做好垃圾清理？</p><p>— name 可以透過注入自己設定的 id 當成 container name ，在後續有多個 sandbox 同時執行時，方便操控指定的 container 。</p><p>到這裡，我們已經可以把前端送來的程式寫檔並執行，剩下的就是如何取得執行的結果了。</p><h4>第四步：取得結果</h4><p>如果我們只做到第三步，會發現程式的確執行了，container 也有跑起來，效能也吃了，所以我說…那個醬…那個結果呢 ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*Tjg3ZiC9ZEwz4G9VJtLOPQ.gif" /><figcaption>圖片來源 ：<a href="https://tenor.com/view/where-are-you-where-you-at-where-cant-see-you-pulp-gif-11929725">https://tenor.com/view/where-are-you-where-you-at-where-cant-see-you-pulp-gif-11929725</a></figcaption></figure><p>這勾起了我的好奇心，我們平常執行程式的 log 是從何而來？原來在每個 Unix 程序啟動時都會產生三個資料 :</p><ul><li>stdin ( Standard Input )：紀錄輸入</li><li>stdout ( Standard Output )：紀錄輸出</li><li>stderr ( Standard Error )：紀錄錯誤</li></ul><p>這些資料可以在 child_process 的 exec 回傳中拿到，所以我們可以透過 callback 或者 Promise / async await 的方式，取得我們找尋已久的結果。</p><pre>async function compile(id, code){<br>  try{<br>    const { stdout } = await exec(<br>      `docker run \<br>      --name ${id} \<br>      -v $(pwd):/code \<br>      --rm runtime-python`,<br>    );<br>    return stdout;<br>  } catch (error){<br>    const { stdout, stderr } = error;<br>    return { stdout, stderr };    <br>  }<br>}</pre><p>完整的 function 會像這樣 :</p><pre>const fs = require(&#39;fs&#39;);<br>const fsPromises = fs.promises;<br>const util = require(&#39;util&#39;);<br>const exec = util.promisify(require(&#39;child_process&#39;).exec);</pre><pre>async function writeFile(code){<br>  await fsPromises.writeFile(`./code.py`, code);<br>}</pre><pre>async function compile(id, code){<br>  try{<br>    await writeFile(code);</pre><pre>    const { stdout } = await exec(<br>      `docker run \<br>      --name ${id} \<br>      -v $(pwd):/code \<br>      --rm runtime-python`,<br>    );</pre><pre>    return stdout;<br>  } catch (error){<br>    const { stdout, stderr } = error;<br>    return { stdout, stderr };    <br>  } finally {<br>    await fsPromises.rm(&#39;./code.py&#39;);<br>  }<br>}</pre><p>這些 functions 再拿到 controller 中去接前端送過來的 code，就可以成功實現 CodeSandbox 的後端功能了！</p><p>那記得最後要再使用 fs 來刪除我們最早建立的 code.py，才不會累績很多執行完的檔案，佔硬碟的空間。</p><h4>結論</h4><p>這篇 code sandbox 只有講到執行的部分，寫檔、準備環境、執行程式和取得結果，實際上還有很多方面要解決，像是如何處理有人寫 while ( true ) 進來時要怎麼辦 ? 程式執行時間很長 ? 很吃效能或記憶體的程式 ? 這些都是要面對的問題，之後有空再把我解決這些問題的方法寫成另一篇。</p><p>最後分享一下近期的心得，挑戰第一個個人專案真的很累，但又覺得很有趣，累得很開心 🤣 ，看到身邊的人都做出各種有趣得作品，也會超好奇想去了解的，只能說希望每天可以不只 24 小時，可以多學一點東西。</p><h4>參考資料</h4><ul><li><a href="https://ithelp.ithome.com.tw/articles/10232335">【我可以你也可以的Node.js】第十六篇 - Node 子行程 child_process - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://docs.docker.com/storage/volumes/">Volumes</a></li><li><a href="https://medium.com/@will.wang/nodejs-and-nodemon-blackhole-2651c7f8307e">不要踏到 Node.js 的黑洞陷阱 👉🕳 😵</a></li><li><a href="https://manpages.ubuntu.com/manpages/bionic/zh_TW/man3/stdin.3.html">Ubuntu Manpage: stdin, stdout, stderr - 標準 I/O 流</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3673b7e6ea06" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>