Files
valheim/Assets/_Valheim/Scripts/HttpServer.cs

121 lines
2.7 KiB
C#

using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using Valheim;
public class HttpServer : MonoBehaviour
{
private HttpListener listener;
private Thread listenThread;
private volatile bool isRunning;
// ❗不要用 +
private const string SERVER_URL = "http://127.0.0.1:12345/";
void Awake()
{
DontDestroyOnLoad(gameObject);
}
IEnumerator Start()
{
// ✅ 让 Unity / XR 先起来
yield return null;
yield return new WaitForSeconds(1.5f);
// ✅ 后台启动
Task.Run(StartServer);
Debug.Log("Http,开始请求");
}
private void StartServer()
{
try
{
listener = new HttpListener();
listener.Prefixes.Add(SERVER_URL);
listener.Start();
isRunning = true;
listenThread = new Thread(ListenLoop)
{
IsBackground = true
};
listenThread.Start();
Debug.Log($"✅ HTTP Server 启动成功:{SERVER_URL}");
}
catch (Exception e)
{
Debug.LogError("❌ HTTP Server 启动失败:" + e);
}
}
private void ListenLoop()
{
while (isRunning)
{
try
{
var context = listener.GetContext();
ProcessRequest(context);
}
catch
{
break;
}
}
}
private void ProcessRequest(HttpListenerContext context)
{
var response = context.Response;
response.ContentType = "application/json; charset=utf-8";
try
{
string json =
$"{{\"code\":200,\"data\":{{\"gameName\":\"{GetGameName()}\"," +
$"\"gameTotalTime\":{GetTotalTime()},\"currentPlayTime\":{GetPlayTime()}}}}}";
byte[] data = Encoding.UTF8.GetBytes(json);
response.OutputStream.Write(data, 0, data.Length);
}
catch (Exception e)
{
Debug.LogError(e);
}
finally
{
response.Close();
}
}
private string GetGameName()
{
return GameInit.Ins != null ? GameInit.Ins.gameId.ToString() : "unknown";
}
private int GetTotalTime()
{
return GameInit.Ins != null ? Mathf.FloorToInt(GameManager .Ins.vistAllTime) : 0;
}
private int GetPlayTime()
{
return GameInit.Ins != null ? GameManager.Ins.GetNowTime() : 0;
}
void OnDestroy()
{
isRunning = false;
listener?.Close();
}
}