97 lines
2.1 KiB
C#
97 lines
2.1 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using UnityEngine;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
public class BootHttpServer : MonoBehaviour
|
|
{
|
|
private HttpListener listener;
|
|
private Thread thread;
|
|
private volatile bool running;
|
|
|
|
private const string URL = "http://+:12345/";
|
|
private bool sceneLoaded = false;
|
|
|
|
void Awake()
|
|
{
|
|
DontDestroyOnLoad(gameObject);
|
|
StartServer();
|
|
}
|
|
|
|
void StartServer()
|
|
{
|
|
try
|
|
{
|
|
listener = new HttpListener();
|
|
listener.Prefixes.Add(URL);
|
|
listener.Start();
|
|
|
|
running = true;
|
|
thread = new Thread(ListenLoop) { IsBackground = true };
|
|
thread.Start();
|
|
|
|
Debug.Log("✅ Boot HTTP Server 已启动");
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Debug.LogError("❌ Boot HTTP 启动失败:" + e);
|
|
}
|
|
}
|
|
|
|
void ListenLoop()
|
|
{
|
|
while (running)
|
|
{
|
|
try
|
|
{
|
|
var ctx = listener.GetContext();
|
|
Handle(ctx);
|
|
}
|
|
catch { }
|
|
}
|
|
}
|
|
|
|
void Handle(HttpListenerContext ctx)
|
|
{
|
|
var resp = ctx.Response;
|
|
resp.ContentType = "application/json";
|
|
resp.AddHeader("Access-Control-Allow-Origin", "*");
|
|
|
|
string json = "{\"code\":200,\"state\":\"booting\"}";
|
|
byte[] buf = Encoding.UTF8.GetBytes(json);
|
|
resp.OutputStream.Write(buf, 0, buf.Length);
|
|
resp.Close();
|
|
|
|
// 第一次收到请求,立刻进主场景
|
|
if (!sceneLoaded)
|
|
{
|
|
sceneLoaded = true;
|
|
UnityMainThread(() =>
|
|
{
|
|
SceneManager.LoadScene(1);
|
|
});
|
|
}
|
|
}
|
|
|
|
void UnityMainThread(Action action)
|
|
{
|
|
// 简单、安全:下一帧执行
|
|
StartCoroutine(InvokeNextFrame(action));
|
|
}
|
|
|
|
IEnumerator InvokeNextFrame(Action act)
|
|
{
|
|
yield return null;
|
|
act?.Invoke();
|
|
}
|
|
|
|
void OnDestroy()
|
|
{
|
|
running = false;
|
|
listener?.Stop();
|
|
}
|
|
}
|