使用HttpListener 实现简单的web服务器

using System;
using System.Net;
using System.IO;
using System.Threading;
using System.Text;
using MySql.Data.MySqlClient;
using System.Collections.Generic;



public class TheServer
{

    private string result = "";
    private MySqlConnection conn;
    private HttpListener _listener;
    private Thread _threadWatchPort;
    private DataBaceTool Tool = new DataBaceTool();
    // private List> Listinfo;

    static void Main(String[] args)
    {
        if (!HttpListener.IsSupported)
        {
            Console.Write("系统不支持HttpListener");
        }
        else
        {
            Console.Write("系统支持HttpListener");
        }
        TheServer Start = new TheServer();

        Start.StartListening();//开始监听
        Start.Tool.OpenDataBace();//打开数据库
                             //  Start.QueryAllData("AirportManager");
    }//检测系统支持不支持
 
    public void StartListening()
    {
        Console.Write("开始监听" );
        _listener = new HttpListener();
        _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
        _listener.Prefixes.Add("http://+:8080/");
        _listener.Start(); //开始监听端口,接收客户端请求
        _threadWatchPort = new Thread(WatchPort);
        _threadWatchPort.Start();
        Console.Write("开启了端口");
    }//开启8080端口并监听

    private void WatchPort()
    {
        while (true)
        {
            try
            {
                HttpListenerContext context = _listener.GetContext(); //等待请求连接,没有请求则GetContext处于阻塞状态
                context.Request.Headers.Add("Access-Control-Allow-Origin", "*");
                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
                HttpListenerRequest request = context.Request; //客户端发送过来的消息
                var reader = new StreamReader(request.InputStream);
                var msg = reader.ReadToEnd();//解析传过来的信息
                //http://192.168.0.1:8080/airport?query=jichang
                Tool.OpenDataBace();
                //上传机场信息
                string inserAirportInfoData = context.Request.QueryString[Messages.insertAirportInfo];
                if (inserAirportInfoData != null)
                {

                    inserAirportInfoData = inserAirportInfoData.Remove(inserAirportInfoData.Length - 18, 18);
                    Tool.ClearDataFromTable("AirportManager");
                    //将字符串转为 数组字典(此处如何解析须与服务端传过来的数据格式匹配)
                    List> infoList = StringToListForDictionary(inserAirportInfoData);
                    Tool.InsertAirportData("AirportManager", infoList);
                }
                HttpListenerResponse response = context.Response;
                context.Response.StatusCode = 200;//设置返回给客服端http状态代码
                string responseString = result;
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length); //服务端发送回消息给客户端
                output.Close();
            }
            catch (Exception exc)
            {
                Console.Write("--有异常-----------" + exc);
                break;
            }

            Console.Write("\n****************************消息处理完成****************************\n");
        }
    }
}

注意此处

string inserAirportInfoData = context.Request.QueryString[Messages.insertAirportInfo];

Messages 是定义的协议类, 通过这个协议参数 来判断 客服端传过的时哪个消息


using System;

public class Messages
{

    public const string insertAirportInfo = "insertAirportInfo";//上传机场信息
    public const string queryAllFlightInfo = "queryAllFlightInfo";//获取航班信息
    public const string queryPlaneInfo = "queryPlaneInfo";//获取飞机数据
    public const string queryLandingPlaneInfo = "queryLandingPlaneInfo";//请求航线降落
    public const string updatePlaneState = "updatePlaneState";//更改飞行状态
    public const string updatePlaneReturn = "updatePlaneReturn";//更改航班时间让航班返航
    public const string insertFlightInfo = "insertFlightInfo";//插入航班面板信息
    public const string queryAirportWeather = "queryAirportWeather";//获取天气
    public const string updateAirportWeather = "updateAirportWeather";//更新天气
    public const string deleteAirline = "deleteAirline";//删除航线 

    public const string queryFlightInfoFromOperation = "queryFlightInfoFromOperation";//查询运行中航班

    /*
     * 飞机状态 0 为起飞  1 飞行中  2 已将落
     * 飞行状态  1 请求降落 0 正在
     * 天气  0 正常 1风  2 雨 3 雪 4 雷电
     * */
}

服务端代码就这些


下面看下客户端如何请求

Message这个协议类 客户端也需要创建个一样的

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


public class QueryData : MonoBehaviour
{

 //   public TextMesh text;
    List> airPortinfoList;
    public delegate void ReturnData(List> list);
    public ReturnData returnAllAirportInfo;
    public ReturnData returnPlaneInfo;
    public ReturnData returnLandingPlaneInfo;
    public ReturnData returnAirportWeather;
    private string resultData = "";

    private IEnumerator coroutine;

	//我这里的key 协议字段 value 时要传个服务器的值
    public IEnumerator RequestServer( string value,string key)
    {
        string url = "http://192.168.0.1:8080/airport?" + key + "=" + value;
        url.Replace(" ", "");//字符串需要过滤掉
        WWW www = new WWW(url);
        yield return www;
        if (string.IsNullOrEmpty(www.error))
        {
            resultData = www.text;
           www.Dispose();
            GetData(key);
        }
    }



    private void GetData(string key)
    {
      //  Debug.Log(key + "============");
        if (resultData.Equals("true"))
        {
            return;
        }
        if(key == Messages.queryAirportWeather)
        {
            if(returnAirportWeather != null)
            {
				//如果有返回值 返回值将在resultData里
                List> list = StringToListForDictionary(resultData);
                returnAirportWeather(list);
            }
        }
       
        return;
    }




你可能感兴趣的:(使用HttpListener 实现简单的web服务器)