12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- using UnityEngine;
- using UnityEngine.Networking;
- using System.Net;
- using System.Threading.Tasks;
- public class HttpServer : MonoBehaviour
- {
- private const string apiUrl = "http://localhost:8080/"; // 接口地址
- private HttpListener httpListener;
- private void Start()
- {
- StartHttpServer();
- }
- private async void StartHttpServer()
- {
- httpListener = new HttpListener();
- httpListener.Prefixes.Add(apiUrl);
- httpListener.Start();
- Debug.Log("HTTP server started.");
- while (httpListener.IsListening)
- {
- HttpListenerContext context = await httpListener.GetContextAsync();
- HandleRequest(context);
- }
- }
- private async void HandleRequest(HttpListenerContext context)
- {
- HttpListenerRequest request = context.Request;
- HttpListenerResponse response = context.Response;
- string responseString = "Hello from Unity!";
- // 处理请求逻辑,根据需要编写自定义的接口实现
- byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
- response.ContentLength64 = buffer.Length;
- response.OutputStream.Write(buffer, 0, buffer.Length);
- response.OutputStream.Close();
- }
- private void OnDestroy()
- {
- if (httpListener != null && httpListener.IsListening)
- {
- httpListener.Stop();
- httpListener.Close();
- }
- }
- }
|