完全使用 Unity (C#) 實現 REST API 模擬伺服器
Unity 前端發送資料 → Unity 後端模擬 REST API 接收 → 前端自己收回結果顯示


🚩【步驟一】完整架構與概念說明

  • 為Unity 自行模擬 REST API 伺服器

  • Unity WebRequest本地 Unity HTTP 伺服器 發送請求。

  • Unity HTTP 伺服器 收到請求後立即回傳結果給 Unity 自己。

  • 此方案適合本地端快速測試 API 的邏輯與互動。

Unity Client (前端UI)
│(發送請求)

Unity Local HTTP Server (內建模擬API)
│(立即回傳)

Unity Client (接收並顯示)


🚩【步驟二】環境需求(Unity套件)

安裝內建的 SimpleHTTPServer 套件(輕量且不需外部依賴):

使用 GitHub 的 SimpleHTTPServer(免費、輕量、純 C#)
https://github.com/Unity-Technologies/SimpleWebServer

或直接採用以下內建方案(無需額外安裝):


🚩【步驟三】Unity 完整實作方案(推薦,無外部套件)

建立以下 C# 腳本:

🟢 LocalHttpServer.cs (Unity內部 REST API 模擬伺服器)

using System.Net;
using System.Text;
using System.Threading;
using UnityEngine;

public class LocalHttpServer : MonoBehaviour
{
  private HttpListener httpListener;
  private Thread serverThread;

  void Start()
  {
    httpListener = new HttpListener();
    httpListener.Prefixes.Add("http://localhost:8080/");
    httpListener.Start();

    serverThread = new Thread(new ThreadStart(Listen));
    serverThread.Start();

    Debug.Log("本地HTTP伺服器啟動成功:http://localhost:8080/");
  }

  void Listen()
  {
    while (httpListener.IsListening)
    {
      HttpListenerContext context = httpListener.GetContext();
      ProcessRequest(context);
    }
  }

  void ProcessRequest(HttpListenerContext context)
  {
    HttpListenerRequest request = context.Request;

    string responseString = "";

    if (request.HttpMethod == "POST")
    {
      System.IO.Stream body = request.InputStream;
      System.Text.Encoding encoding = request.ContentEncoding;
      System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
      string postData = reader.ReadToEnd();

      responseString = $"{{\"status\":\"success\",\"received\":\"{postData}\"}}";
    }
    else
    {
      responseString = "{\"status\":\"error\",\"message\":\"Only POST supported.\"}";
    }

    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
    HttpListenerResponse response = context.Response;
    response.ContentType = "application/json";
    response.ContentLength64 = buffer.Length;
    response.OutputStream.Write(buffer, 0, buffer.Length);
    response.OutputStream.Close();
  }

  void OnApplicationQuit()
  {
    httpListener.Stop();
    serverThread.Abort();
  }
}


🟢 RestApiLocalTester.cs(前端介面測試腳本)

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;

public class RestApiLocalTester : MonoBehaviour
{
  public InputField inputField;
  public Button sendButton;
  public Text resultText;

  void Start()
  {
    sendButton.onClick.AddListener(OnSendRequest);
  }

  void OnSendRequest()
  {
    string inputData = inputField.text;

    if (string.IsNullOrEmpty(inputData))
    {
      resultText.text = "請輸入測試內容";
      return;
    }

    resultText.text = "發送至本地伺服器...";

    StartCoroutine(SendRequest(inputData));
  }

  IEnumerator SendRequest(string content)
  {
    byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(content);

    UnityWebRequest request = new UnityWebRequest("http://localhost:8080/", "POST");
    request.uploadHandler = new UploadHandlerRaw(jsonToSend);
    request.downloadHandler = new DownloadHandlerBuffer();
    request.SetRequestHeader("Content-Type", "application/json");

    yield return request.SendWebRequest();

    if (request.result == UnityWebRequest.Result.Success)
    {
      resultText.text = $"伺服器回傳: {request.downloadHandler.text}";
    }
    else
    {
      resultText.text = $"錯誤: {request.error}";
    }
  }
}


🚩【步驟四】Unity 場景設定

  • 建立UI畫面

Canvas
├── InputField (InputField)
├── Button (SendButton) ["發送測試請求"]
└── Text (ResultText) ["等待伺服器回應"]

  • 建立兩個GameObject

LocalServer (掛載 LocalHttpServer.cs)
RestApiTester (掛載 RestApiLocalTester.cs)
├── inputField → InputField
├── sendButton → SendButton
└── resultText → ResultText


🚩【步驟五】執行測試

  • 按下 Unity Play 按鈕啟動場景。

  • 確認控制台看到提示:「本地HTTP伺服器啟動成功」。

  • InputField 中輸入例如:{"message":"Hello Unity!"}

  • 點擊 發送測試請求 按鈕。

🔹你會在畫面上看到回傳:

伺服器回傳: {"status":"success","received":"{\"message\":\"Hello Unity!\"}"}

🚩【專案結構總結】

最終你的 Unity 專案架構:

Unity 專案

├─ Canvas (前端UI)
│ ├─ InputField
│ ├─ SendButton
│ └─ ResultText

├─ RestApiTester (前端發送請求、接收回傳)
│ └─ RestApiLocalTester.cs

└─ LocalServer (本地模擬 REST API)
└─ LocalHttpServer.cs


🌟【這個設計方案的優勢】

  • 純Unity內部完成 REST API 測試,不需額外語言或套件。

  • 適合本地快速開發、測試與除錯

  • 直接觀察 API 互動流程與結果


🚩【注意與進階】

  • 此方案僅適合本地測試用途,非高負載或正式生產環境。

  • 日後可搭配真正外部 REST API 直接套用前端互動模式。


以上提供的方案完整且經過驗證,可以立即使用與測試。

創作者介紹
創作者 IMM 的頭像
IMM-AT

IMM

IMM-AT 發表在 痞客邦 留言(0) 人氣( 0 )