栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

在unity内创建http服务器(C#)

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在unity内创建http服务器(C#)

c#中可以使用HttpListener实现简单的http服务端。

调用SimpleHttpSer.StartSer( 端口);开启服务器

SimpleHttpSer.StopServer()关闭

using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using UnityEngine;
using System.Collections.Specialized;
using System.Collections.Concurrent;
using System.IO;
using System.Collections;

using LitJson;

enum GCode
{
    OK=200,                 // 正确
    ERR = 500,            // 未知错误
    ERR_PARAM=501,          // 参数错误
}

public class SimpleHttpSer
{
    static HttpListener httpobj = null;            // http服务器

    // 开启服务器
    public static void StartServer( int port)
    {
        //提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。
        httpobj = new HttpListener();
        //定义url及端口号,通常设置为配置文件
        httpobj.Prefixes.Add("http://+:"+port+"/");
        // 启动监听
        httpobj.Start();
        //异步监听客户端请求,当客户端的网络请求到来时会自动执行OnReqResult委托
        //该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
        httpobj.BeginGetContext(OnReqResult, null);
    }
    // 关闭服务器
    public static void StopServer()
    {
        if( httpobj != null)
        {
            httpobj.Stop();
            httpobj = null;
        }
    }
    // 有网络请求
    private static void onReqResult(IAsyncResult ar)
    {
        //当接收到请求后程序流会走到这里
        //继续异步监听
        httpobj.BeginGetContext(OnReqResult, 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");//后台跨域请求设置,通常设置为配置文件
        response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
        response.AddHeader("Content-type", "text/plain");//添加响应头信息
        response.ContentEncoding = Encoding.UTF8;
        string returnObj = null;//定义返回客户端的信息
        if ( request.HttpMethod == "GET")
        {
            // 处理get请求
            returnObj = onGet( request, response);
        } 
        else if (request.HttpMethod == "POST")
        {
            // 处理post请求
            returnObj = onPost( request, response);
        } 
        else
        {
            returnObj = PackRespone( GCode.ERR, null);
        }
        var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码
        response.ContentLength64 = returnByteArr.Length;
        try
        {
            using (var stream = response.OutputStream)
            {
                //把处理信息返回到客户端
                stream.Write(returnByteArr, 0, returnByteArr.Length);
                stream.Flush();
            }
        }
        catch (Exception )
        {
        }
        response.Close();
    }

    // 封装返回的字符串
    static string PackRespone( GCode errCode, JsonData infoData)
    {
        JsonData json = new JsonData();
        json["status"] = (int)errCode;
        if( infoData != null)
        {
            json["info"] = infoData;
        }
        return GFun.JsonToStr(json);
    }

    private static string onGet(HttpListenerRequest request, HttpListenerResponse response)
    {
        // 请求的参数字段
        NamevalueCollection queryInfo = request.QueryString;
        // 请求的子路径 
        string rawUrl = request.RawUrl;
        // 这里处理get请求的具体事务

        return PackRespone( GCode.OK, null);
    }

    // 处理post请求
    private static string onPost(HttpListenerRequest request, HttpListenerResponse response)
    {
        // 请求的参数字段
        NamevalueCollection reqInfo = new NamevalueCollection();
        // 请求的子路径 
        string rawUrl = request.RawUrl;
        // post过来的body内容 request.InputStream
        // 这里处理post请求的具体事务
        
        return PackRespone( GCode.OK, null);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/468728.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号