Unity Http通信


一、Unity 使用Http发送消息

public class HttpManager
{
    
    
    /// <summary>
    /// 发送单条消息
    /// </summary>
    /// <param name="url"></param>
    /// <param name="order"></param>
    public static void PostSend(string url, string Content, Action<string> Callback = null)
    {
    
    
        try
        {
    
    
        	//增加这句是为使用Https时,防止报错
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            WebClient wc = new WebClient();
            //可修改为不同的ContentType
            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            //发送到服务端并获得返回值
            wc.UploadDataAsync(new Uri(url), "POST", Encoding.UTF8.GetBytes(Content));
            wc.UploadDataCompleted += new UploadDataCompletedEventHandler((sender, e) =>
            {
    
    
                string str = Encoding.UTF8.GetString(e.Result);
                if (Callback != null)
                {
    
    
             		//如果回调涉及UI变化或者使用Texture等的实例化时,此处可使用Loom转到主线程操作
                 	Callback(str);
                }
            });
        }
        catch (Exception e)
        {
    
    
            Debug.Log(e);
        }
    }

    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
    
    
        return true;
    }
}

二、Unity 创建Http服务,接收http消息

using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using UnityEngine;

public class HttpProcessor : MonoBehaviour
{
    
    
    public int port = 8080;

    private HttpListener httpListener;

    private void Awake()
    {
    
    
        httpListener = new HttpListener();
        //定义url及端口号
        httpListener.Prefixes.Add(string.Format("http://+:{0}/", port));
        //启动监听器
        httpListener.Start();
        //异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
        //该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
        httpListener.BeginGetContext(Result, null);
        Debug.Log("Http启动 :" + DateTime.Now.ToString());
    }

    /// <summary>
    /// 消息接收
    /// </summary>
    /// <param name="ar"></param>
    private void Result(IAsyncResult ar)
    {
    
    
        //继续异步监听
        httpListener.BeginGetContext(Result, null);
        var guid = Guid.NewGuid().ToString();
        //Debug.Log("接到新的请求:" + guid + ",时间:" + DateTime.Now.ToString());
        //获得context对象
        var context = httpListener.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 returnMsg = null;//返回客户端的信息
        if (request.HttpMethod == "POST" && request.InputStream != null)
        {
    
    
            returnMsg = HandleRequest(request, response);
        }
        else
        {
    
    
            returnMsg = "不是post请求或者传过来的数据为空";
        }
        var returnByteArr = Encoding.UTF8.GetBytes(returnMsg);//设置客户端返回信息的编码
        try
        {
    
    
            using (var stream = response.OutputStream)
            {
    
    
                //把处理信息返回到客户端
                stream.Write(returnByteArr, 0, returnByteArr.Length);
            }
        }
        catch (Exception ex)
        {
    
    
            Debug.Log("网络异常:" + ex.ToString());
        }
    }

    /// <summary>
    /// 消息处理
    /// </summary>
    /// <param name="request"></param>
    /// <param name="response"></param>
    /// <returns></returns>
    private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response)
    {
    
    
        try
        {
    
    
            List<byte> byteList = new List<byte>();
            byte[] byteArr = new byte[4096];
            int readLen = 0;
            int len = 0;
            //接收客户端传过来的数据并转成字符串类型
            do
            {
    
    
                readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);
                len += readLen;
                byteList.AddRange(byteArr);
            } while (readLen != 0);
            string data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);

            //获取得到数据data可以进行其他操作
            response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
            response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。

            Debug.Log("接收到的Http请求内容:" + data);
            return "success";
        }
        catch (Exception ex)
        {
    
    
            response.StatusDescription = "404";
            response.StatusCode = 404;
            Debug.Log("在接收数据时发生错误:" + ex.ToString());
            return "在接收数据时发生错误:" + ex.ToString();//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考
        }
    }
}

创建Http服务后即可使用使用postman等工具或浏览器地址栏输入链接测试是否正常收发消息。

总结

以上使用的都是Post的请求方式,如果想使用Get请求,自行在Post部分修改为Get即可,其他并无大的变化。关于ContentType、Header等的设置也需个人通过项目实际需求进行设置。

猜你喜欢

转载自blog.csdn.net/qq_27050589/article/details/125715311