using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Net; using System.Threading; using QFrameworkCP; using System.Text; namespace JXSoft { public class HttpServerModel : DataEventModel { protected override void OnInit() { } public override void setLinkState(int linkState) { } public override int getLinkState() { return 0; } } public class HttpServerUtility:IUtility { //example:http://127.0.0.1:8080/index public string address; public HttpListener httpServer; public bool isReceivedValue = false; public string receivedData = ""; public string exceptionData = ""; public Thread reciveT; public bool startServer(string[] prefixes) { if (!httpServer.IsListening) { if (!HttpListener.IsSupported) { Debug.Log("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); return false; } // URI prefixes are required, // for example "http://127.0.0.1:8080/index/". if (prefixes == null || prefixes.Length == 0) { throw new ArgumentException("prefixes"); } // Create a listener. httpServer = new HttpListener(); // Add the prefixes. foreach (string s in prefixes) { httpServer.Prefixes.Add(s); } httpServer.Start(); Debug.Log("Listening..."); return true; } return false; } public void startServer(string prefix) { string[] prefixes = {prefix}; startServer(prefixes); } public void startServer() { string[] prefixes = { address }; startServer(prefixes); } public void closeServer() { if (httpServer.IsListening) { httpServer.Stop(); } } public void RecciveMsg() { byte[] receiveBuff = new byte[1024]; int reviceLength = 0; string msg = ""; while (httpServer.IsListening) { try { HttpListenerContext context = httpServer.GetContext(); HttpListenerRequest request = context.Request; // Obtain a response object. //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(request.Url); //reviceLength = tcpClient.Client.Receive(receiveBuff); msg = Encoding.UTF8.GetString(receiveBuff, 0, reviceLength); if (msg != "") { receivedData = msg; isReceivedValue = true; } } catch (Exception e) { Debug.LogWarning(e); //断线发送异常 exceptionData = e.ToString(); break; } } Debug.Log("------------end While-------------"); } /// /// 线程接收到消息后 /// /// 接收到的消息 public string getReceivedValue() { if (isReceivedValue) { isReceivedValue = false; return receivedData; } else { return ""; } } } }