using System; using System.Collections; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; using UnityEngine.Networking; namespace NBF { [Serializable] public class HttpResult { public int Code { get; set; } public JToken Data { get; set; } } class NetData { public string action; public Dictionary form; public Action callback = null; public bool Success = false; public void Send() { } } public class Net : MonoBehaviour { public string ServerUrl { get; private set; } = "http://localhost:8080"; private string serverPassword = ""; public static Net Instance { get; private set; } public event Action OnError; private string DeviceId; private string DeviceName; Queue _netDataQueue = new Queue(); private void Awake() { Instance = this; } private void Start() { DeviceId = PlatformInfo.GetAndroidID(); DeviceName = PlatformInfo.GetDeviceModel(); } public void SetServer(string server, string password) { if (!(server.StartsWith("http://") || server.StartsWith("https://"))) { server = "http://" + server; } if (server.EndsWith("/")) { server = server.Substring(0, server.Length - 1); } else if (server.EndsWith("\\")) { server = server.Substring(0, server.Length - 1); } ServerUrl = server; serverPassword = password; } public void Tick(int id, int time, int count, Action callback = null) { var dic = new Dictionary { { "device", DeviceId }, { "deviceName", DeviceName }, { "id", id.ToString() }, { "time", time.ToString() }, { "watchCount", count.ToString() } }; Send("/api/tick", dic, callback); } #region Post public void Send(string action, Dictionary form, Action callback = null) { StartCoroutine(SendYield(action, form, callback)); } private IEnumerator SendYield(string action, Dictionary form, Action callback = null) { if (form == null) { form = new Dictionary(); } var url = ServerUrl + action; form["sign"] = serverPassword; UnityWebRequest request = UnityWebRequest.Post(url, form); request.downloadHandler = new DownloadHandlerBuffer(); Debug.Log("Request: " + JsonConvert.SerializeObject(form)); // 4️⃣ 发送 yield return request.SendWebRequest(); // 5️⃣ 处理结果 if (request.result != UnityWebRequest.Result.Success) { Debug.LogError(request.error); callback?.Invoke(new HttpResult() { Code = -1, Data = request.error }); OnError?.Invoke(request.result, request.error); } else { Debug.Log("Response: " + request.downloadHandler.text); var result = JsonConvert.DeserializeObject(request.downloadHandler.text); callback?.Invoke(result); } } #endregion } }