客戶端
using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using Newtonsoft.Json; using UnityEngine; public class TestHttp : MonoBehaviour { private WebClient wc; private string url = "http://localhost:8079"; private Thread thread; // Start is called before the first frame update void Start() { CreateWebClient(); thread = new Thread(SendHttpMsg); Debug.Log("按K鍵發送消息"); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.K)) { //異步 Action ac = SendHttpMsg; ac.BeginInvoke(null,null); //同步 //SendHttpMsg(); //線程 //thread.Start(); } } void CreateWebClient() { wc = new WebClient(); } /// <summary> /// 向服務器發送消息 /// </summary> void SendHttpMsg() { Debug.Log($"請求服務地址:{url},時間:{DateTime.Now.ToString()}"); //模擬一個json數據發送到服務端 var data = new Data(1, "張三"); var jsonModel = JsonConvert.SerializeObject(data); //發送到服務端並獲得返回值 byte[] returnInfo; try { returnInfo = wc.UploadData(url, Encoding.UTF8.GetBytes(jsonModel)); } catch (Exception e) { Debug.LogError("url可能不對,或者遠程服務器關閉,或者連接失敗"); Debug.LogError(e); return; } //把服務端返回的信息轉成字符串 var str = Encoding.UTF8.GetString(returnInfo); Debug.Log($"服務端返回信息:{str},時間:{DateTime.Now.ToString()}"); } } class Data { public Data(int id, string name) { this.ID = id; this.Name = name; } public int ID { get; set; } public string Name { get; set; } }
服務端
using System; using System.Collections.Generic; using System.Net; using System.Text; namespace HttpServer { internal class Program { static HttpListener httpobj; public static void Main(string[] args) { //提供一個簡單的、可通過編程方式控制的 HTTP 協議偵聽器。此類不能被繼承。 httpobj = new HttpListener(); //定義url及端口號,通常設置為配置文件 //httpobj.Prefixes.Add("http://+:8089/"); httpobj.Prefixes.Add("http://localhost:8079/"); //啟動監聽器 httpobj.Start(); //異步監聽客戶端請求,當客戶端的網絡請求到來時會自動執行Result委托 //該委托沒有返回值,有一個IAsyncResult接口的參數,可通過該參數獲取context對象 httpobj.BeginGetContext(Result, null); Console.WriteLine($"服務端初始化完畢,正在等待客戶端請求,時間:{DateTime.Now.ToString()}\r\n"); Console.ReadKey(); } private static void Result(IAsyncResult ar) { //當接收到請求后程序流會走到這里 //繼續異步監聽 httpobj.BeginGetContext(Result, null); var guid = Guid.NewGuid().ToString(); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"接到新的請求:{guid},時間:{DateTime.Now.ToString()}"); //獲得context對象 var context = httpobj.EndGetContext(ar); var request = context.Request; var response = context.Response; ////如果是js的ajax請求,還可以設置跨域的ip地址與參數 //context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域請求,通常設置為配置文件 //context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域參數設置,通常設置為配置文件 //context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域請求設置,通常設置為配置文件 context.Response.ContentType = "text/plain;charset=UTF-8";//告訴客戶端返回的ContentType類型為純文本格式,編碼為UTF-8 context.Response.AddHeader("Content-type", "text/plain");//添加響應頭信息 context.Response.ContentEncoding = Encoding.UTF8; string returnObj = null;//定義返回客戶端的信息 if (request.HttpMethod == "POST" && request.InputStream != null) { //處理客戶端發送的請求並返回處理信息 returnObj = HandleRequest(request, response); } else { returnObj = $"不是post請求或者傳過來的數據為空"; } var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//設置客戶端返回信息的編碼 try { using (var stream = response.OutputStream) { //把處理信息返回到客戶端 stream.Write(returnByteArr, 0, returnByteArr.Length); } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"網絡蹦了:{ex.ToString()}"); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"請求處理完成:{guid},時間:{ DateTime.Now.ToString()}\r\n"); } private static string HandleRequest(HttpListenerRequest request, HttpListenerResponse response) { string data = null; try { var byteList = new List<byte>(); var byteArr = new byte[2048]; int readLen = 0; int len = 0; //接收客戶端傳過來的數據並轉成字符串類型 do { readLen = request.InputStream.Read(byteArr, 0, byteArr.Length); len += readLen; byteList.AddRange(byteArr); } while (readLen != 0); data = Encoding.UTF8.GetString(byteList.ToArray(),0, len); //獲取得到數據data可以進行其他操作 } catch (Exception ex) { response.StatusDescription = "404"; response.StatusCode = 404; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"在接收數據時發生錯誤:{ex.ToString()}"); return $"在接收數據時發生錯誤:{ex.ToString()}";//把服務端錯誤信息直接返回可能會導致信息不安全,此處僅供參考 } response.StatusDescription = "200";//獲取或設置返回給客戶端的 HTTP 狀態代碼的文本說明。 response.StatusCode = 200;// 獲取或設置返回給客戶端的 HTTP 狀態代碼。 Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"接收數據完成:{data.Trim()},時間:{DateTime.Now.ToString()}"); return $"接收數據完成"; } } }
