在Unity快速搭建一个接收http请求

感谢https://www.cnblogs.com/ggll611928/p/15726839.html

using Unity.Plastic.Newtonsoft.Json.Linq;
using Unity.Plastic.Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

namespace WFHttpServer
{
    /// 
    ///  通过HttpListener实现简单的http服务器
    /// 
    public class HttpListenerServer
    {
        /// 
        /// 启动监听
        /// 
        /// 监听的多个地址
        public void Start(HttpListener _listener, string  prefixes)
        {
            // 增加监听的前缀
            _listener.Prefixes.Add(prefixes);

            _listener.Start(); //开始监听
            _listener.BeginGetContext(GetContextCallBack, _listener);
        }

        private void GetContextCallBack(IAsyncResult ar)
        {
            try
            {
                HttpListener _listener = ar.AsyncState as HttpListener;
                if (_listener.IsListening)
                {
                    HttpListenerContext context = _listener.EndGetContext(ar);
                    _listener.BeginGetContext(new AsyncCallback(GetContextCallBack), _listener);

                    #region 解析Request请求

                    HttpListenerRequest request = context.Request;
                    string content = "";
                    switch (request.HttpMethod)
                    {
                        case "POST":
                            {
                                Stream stream = context.Request.InputStream;
                                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                                content = reader.ReadToEnd();
                                Debug.LogError("-------------"+ content);
                                //模拟接受的数据:将接收的字符串内容进行json反序列号为对象
                                //TestValue tv = JsonConvert.DeserializeObject(content);
                                //根据需求做相应操作
                            }
                            break;
                        case "GET":
                            {
                                var data = request.QueryString;
                                Debug.LogError("-------------" + data);
                            }
                            break;
                    }

                    #endregion

                    #region 构造Response响应

                    HttpListenerResponse response = context.Response;
                    response.StatusCode = (int)HttpStatusCode.OK;
                    response.ContentType = "application/json;charset=UTF-8";
                    response.ContentEncoding = Encoding.UTF8;
                    response.AppendHeader("Content-Type", "application/json;charset=UTF-8");

                    模拟返回的数据:Json格式
                    //var abcOject = new
                    //{
                    //    code = "200",
                    //    description = "success",
                    //    data = "time=" + DateTime.Now
                    //};
                    //string responseString = JsonConvert.SerializeObject(abcOject,
                    //    new JsonSerializerSettings()
                    //    {
                    //        StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
                    //    });

                    //using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
                    //{
                    //    writer.Write(responseString);
                    //    writer.Close();
                    //    response.Close();
                    //}

                    #endregion

                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ex.Message);
            }
        }
    }


    //用于json反序列化获取的测试实体类
    public class TestValue
    {
        public int id { get; set; }
        public string name { get; set; }
    }


}
    private void btnStart_Click( )
    {
        Debug.LogError("--------btnStart_Click----11-----");
        //获取监听的多个地址
        string ipAddress1 = "http://127.0.0.1:8033/"; 

        // 注意前缀必须以 / 正斜杠结尾 
        HttpListenerServer httpListenerServer = new HttpListenerServer();
        try
        {
            // 检查系统是否支持
            if (!HttpListener.IsSupported)
            {
                throw new ArgumentException("使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
            }
            else
            {
                //启动监听 // 创建监听器.
                _listener = new HttpListener();
                httpListenerServer.Start(_listener, ipAddress1);
            }
        }
        catch (Exception ex)
        { 
        }
    }

你可能感兴趣的:(unity,http,游戏引擎)