HttpServer.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using System.Net;
  4. using System.Threading.Tasks;
  5. public class HttpServer : MonoBehaviour
  6. {
  7. private const string apiUrl = "http://localhost:8080/"; // 接口地址
  8. private HttpListener httpListener;
  9. private void Start()
  10. {
  11. StartHttpServer();
  12. }
  13. private async void StartHttpServer()
  14. {
  15. httpListener = new HttpListener();
  16. httpListener.Prefixes.Add(apiUrl);
  17. httpListener.Start();
  18. Debug.Log("HTTP server started.");
  19. while (httpListener.IsListening)
  20. {
  21. HttpListenerContext context = await httpListener.GetContextAsync();
  22. HandleRequest(context);
  23. }
  24. }
  25. private async void HandleRequest(HttpListenerContext context)
  26. {
  27. HttpListenerRequest request = context.Request;
  28. HttpListenerResponse response = context.Response;
  29. string responseString = "Hello from Unity!";
  30. // 处理请求逻辑,根据需要编写自定义的接口实现
  31. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
  32. response.ContentLength64 = buffer.Length;
  33. response.OutputStream.Write(buffer, 0, buffer.Length);
  34. response.OutputStream.Close();
  35. }
  36. private void OnDestroy()
  37. {
  38. if (httpListener != null && httpListener.IsListening)
  39. {
  40. httpListener.Stop();
  41. httpListener.Close();
  42. }
  43. }
  44. }