構建伺服器

在本篇文章中,我們將為我們的手機應用設定伺服器。伺服器檔案看起來會像一個普通的 Express 伺服器檔案,但有一個區別:Peer 伺服器。

  1. 首先,在與之前建立的 HTML 和 CSS 檔案相同的位置建立一個名為 server.js 的檔案。根據我們在 package.json 檔案中的定義,這是我們應用的入口點。

  2. 您需要在 server.js 檔案的頂部透過 `require` peer 伺服器來啟動您的程式碼,以確保我們能夠訪問 peer 伺服器。

    js
    const { ExpressPeerServer } = require("peer");
    
  3. 然後,您需要實際建立 peer 伺服器。在上一行程式碼下方新增以下程式碼:

    js
    const peerServer = ExpressPeerServer(server, {
      proxied: true,
      debug: true,
      path: "/myapp",
      ssl: {},
    });
    

    我們使用 ExpressPeerServer 物件來建立 peer 伺服器,並在過程中傳遞一些選項。peer 伺服器將為我們處理 WebRTC 所需的信令,因此我們無需擔心 STUN/TURN 伺服器或其他協議。

  4. 最後,您需要透過呼叫 app.use(peerServer) 來告訴您的應用使用 peerServer。您完成後的 server.js 檔案應包含您在伺服器檔案中會包含的其他必需依賴項,並在根路徑上提供 index.html 檔案。

    更新 server.js 使其看起來像這樣:

    js
    const express = require("express");
    const http = require("http");
    const path = require("path");
    const { ExpressPeerServer } = require("peer");
    
    const app = express();
    const server = http.createServer(app);
    const port = process.env.PORT || "8000";
    
    const peerServer = ExpressPeerServer(server, {
      proxied: true,
      debug: true,
      path: "/myapp",
      ssl: {},
    });
    
    app.use(peerServer);
    
    app.use(express.static(path.join(__dirname)));
    
    app.get("/", (request, response) => {
      response.sendFile(`${__dirname}/index.html`);
    });
    
    server.listen(port);
    console.log(`Listening on: ${port}`);
    
  5. 您應該可以透過 localhost 連線到您的應用(在我們的 server.js 中,我們使用埠 8000,但您可能正在使用其他埠號)。在您的終端中執行 yarn start(其中 start 指的是您在前一頁的 package.json 中宣告的指令碼)。在瀏覽器中訪問 localhost:8000,您應該會看到一個如下所示的頁面:

    A cream background with the words 'phone a friend' in bold, dark green font as the heading. 'Connecting...' is immediately below that and 'please use headphones!' below that. Following on, a big dark green button with 'Call' written in the same cream color of the background.

如果您想了解更多關於 Peer.js 的資訊,請檢視 GitHub 上的 Peer.js Server 倉庫