您的位置:首页 > 教育 > 锐评 > Unity创建简单的Http服务器/客户端测试

Unity创建简单的Http服务器/客户端测试

2024/10/6 8:24:27 来源:https://blog.csdn.net/Tel17610887670/article/details/139664255  浏览:    关键词:Unity创建简单的Http服务器/客户端测试

服务器部分:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using UnityEngine;/// <summary>
/// 服务器部分
/// </summary>
public class Sever_Yang : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){IniHttpServer();}// Update is called once per framevoid Update(){}MyHttpServer HttpServer;public void IniHttpServer(){HttpServer = new MyHttpServer(new string[]{"http://127.0.0.1:8080/"});//绑定映射,处理函数//当传入URL为"http://127.0.0.1:8080/PostAGVC_Data/"时将调用PostAGVC_Data函数接收和解析HttpServer.AddRoute("/PostData_Login/", PostData_Login);//当传入URL为"http://127.0.0.1:8080/PostAGV_Data/"时将调用PostAGV_Data函数接收和解析HttpServer.AddRoute("/PostAGV_Data/", PostAGV_Data);HttpServer.Start();}public async Task<string> PostData_Login(HttpListenerContext context){string httpMethod = context.Request.HttpMethod;string responseString = "";// 处理 POST 请求if (context.Request.HasEntityBody){// 从请求主体中获取数据using (System.IO.Stream body = context.Request.InputStream){using (System.IO.StreamReader reader = new System.IO.StreamReader(body, context.Request.ContentEncoding)){string postData = reader.ReadToEnd(); // 读取 POST 数据//处理数据Debug.LogError(postData);                                    //。。。。。。。。。。。。//。。。。。。。。。。。。//返回字符串responseString = "OK";}}}return responseString;}//与PostAGVC_Data内部类似,处理数据的代码不一样public async Task<string> PostAGV_Data(HttpListenerContext context){//省略Console.WriteLine(111);return null;}
}class MyHttpServer
{private readonly string mUrl; // 服务器监听的URLprivate readonly HttpListener mListener; // HttpListener实例private readonly Dictionary<string, Func<HttpListenerContext, Task<string>>> mRoutes; // 路由映射// 构造函数,接收服务器监听地址和端口的数组public MyHttpServer(string[] prefixes){if (!HttpListener.IsSupported){throw new NotSupportedException("HttpListener is not supported on this platform.");}mListener = new HttpListener(); // 初始化HttpListener实例mRoutes = new Dictionary<string, Func<HttpListenerContext, Task<string>>>(); // 初始化路由映射字典// 为服务器添加监听地址和端口foreach (string prefix in prefixes){mListener.Prefixes.Add(prefix);}mUrl = prefixes[0]; // 记录第一个监听地址}public bool IsOpen { get { return mListener.IsListening; } }// 启动服务器public void Start(){mListener.Start();Console.WriteLine($"Server started and listening on {mUrl}");mListener.BeginGetContext(ProcessRequestCallback, mListener); // 处理客户端请求}// 停止服务器public void Stop(){mListener.Stop();mListener.Close();Console.WriteLine("Server stopped.");}// 添加路由和处理程序的映射关系public void AddRoute(string route, Func<HttpListenerContext, Task<string>> handler){mRoutes.Add(route, handler);}// 处理客户端请求的回调函数private async void ProcessRequestCallback(IAsyncResult result){HttpListener listener = (HttpListener)result.AsyncState;// 开始下一个请求的监听listener.BeginGetContext(ProcessRequestCallback, listener);try{// 获取传入的请求HttpListenerContext context = listener.EndGetContext(result);// 获取请求方法和URL路径string httpMethod = context.Request.HttpMethod;string responseString = "No Data!"; // 默认响应字符串string url = context.Request.Url.AbsolutePath;Func<HttpListenerContext, Task<string>> handler;// 如果请求路径存在于路由映射中,执行相应的处理程序if (mRoutes.TryGetValue(url, out handler)){responseString = await handler(context); // 获取处理程序返回的响应数据// 将响应数据编码成字节数组byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);// 设置响应的内容长度和状态码context.Response.ContentLength64 = buffer.Length;context.Response.StatusCode = (int)HttpStatusCode.OK;// 将响应写入输出流并关闭输出流context.Response.OutputStream.Write(buffer, 0, buffer.Length);context.Response.OutputStream.Close();}else{// 如果请求路径不存在于路由映射中,返回404 Not Foundcontext.Response.StatusCode = (int)HttpStatusCode.NotFound;context.Response.Close();}}catch (Exception ex){Console.WriteLine($"Error processing request: {ex.Message}");}}
}

客户端部分:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;/// <summary>
/// 客户端部分
/// </summary>
public class MyHttpClient : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){IniHttpClient();}HttpClient_DP HttpClient;public void IniHttpClient(){if (HttpClient == null){HttpClient = new HttpClient_DP();HttpClient.TimeOut = TimeSpan.FromSeconds(10);}}// Update is called once per framevoid Update(){if (Input.GetKeyDown(KeyCode.A)){Debug.LogError("发送报文");//Debug.LogError(HttpClient.Post("http://192.168.9.12:8080/PostData_Login/", "发送报文格式"));SenMessage("PostData_Login","报文格式");}}public async void SenMessage(string _post, string _str){string _pp = await HttpClient.Post(_post, _str,DisposeData);}//数据处理public void DisposeData(string _post, string _str){Debug.LogError("接收端口" + _post + "  \n报文json:" + _str);}}public class HttpClient_DP
{private readonly HttpClient _client; // HttpClient 实例// 构造函数,初始化 HttpClient 实例public HttpClient_DP(){_client = new HttpClient();}// 设置超时时间public TimeSpan TimeOut { set { _client.Timeout = value; } }// 发送 GET 请求并返回响应内容public async Task<string> Get(string url){HttpResponseMessage response = await _client.GetAsync(url); // 发送 GET 请求if (response.IsSuccessStatusCode){string content = await response.Content.ReadAsStringAsync(); // 读取响应内容return content;}else{return $"Error: {response.StatusCode}"; // 返回错误信息}}// 发送 POST 请求并返回响应内容public async Task<string> Post(string _post, string data,Action<string,string> _ac){var url = GetUrl(_post);HttpContent content = new StringContent(data); // 创建包含请求数据的 HttpContent 实例Debug.LogError(111);HttpResponseMessage response = await _client.PostAsync(url, content); // 发送 POST 请求Debug.Log(response.IsSuccessStatusCode);if (response.IsSuccessStatusCode){string responseData = await response.Content.ReadAsStringAsync(); // 读取响应内容Debug.LogError(responseData);_ac?.Invoke(_post, responseData);return responseData;}else{return $"Error: {response.StatusCode}"; // 返回错误信息}}public string GetUrl(string _post){return "http://127.0.0.1:8080/" + _post + "/";}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com