自定义服务器,并宿主在 WPF 程序中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using CMApplication1.Views;
using System.Net;
using System.IO;
namespace CMApplication1.ViewModels
{
    [Description("实现简易 IIS,宿主在 WPF 中")]
    [Export(typeof(SimpleIISViewModel))]
    public class SimpleIISViewModel : PropertyChangedBase, IShell
    {
        private SimpleIISView SimpleIISViewSelf;
        string basePath = @"E:\Html5\UIKit";
        public void Load(SimpleIISView view)
        {
            SimpleIISViewSelf = view;
            if (HttpListener.IsSupported)
            {
                //HttpListener listener = new HttpListener();
                //listener.Prefixes.Add("http://192.168.1.117:9988/");
                //listener.Start();
                //Console.WriteLine("开始服务");
                //while (true)
                //{
                //    Console.Write(DateTime.Now.ToString());
                //    HttpListenerContext context = listener.GetContext();
                //    //string page = context.Request.Url.LocalPath.Replace("/", "");
                //    //String query = context.Request.Url.Query.Replace("?", "");
                //    StreamReader sr = new StreamReader(context.Request.InputStream);
                //    Console.WriteLine(sr.ReadToEnd());
                //    //请求资源路径
                //    string page = context.Request.Url.LocalPath.Replace("/", "\\");
                //    string res = string.Format("{0}{1}", basePath, page);
                //    String query = context.Request.Url.Query.Replace("?", "");
                //    Console.WriteLine("接收到请求:{0}?{1}", res, query);
                //    StreamWriter sw = new StreamWriter(context.Response.OutputStream);
                //    string result = string.Empty;
                //    if (page == "\\")
                //    {
                //        result = File.ReadAllText(@"E:\Html5\UIKit\index.html");
                //    }
                //    else
                //    {
                //        if (File.Exists(res))
                //        {
                //            result = File.ReadAllText(res);
                //        }
                //    }
                //    Console.WriteLine(result);
                //    sw.Write(result);
                //    sw.Flush();
                //    context.Response.Close();
                //}
                //Start();
                //Console.WriteLine("正在监听中....");
                //while (true)
                //{
                //    System.Threading.Thread.Sleep(2000);
                //}
                try
                {
                    listener = new HttpListener();
                    //这里开启Http 监听
                    listener.Prefixes.Add("http://192.168.1.117:9988/");//也支持域名形式
                    listener.Start();
                    Console.WriteLine("正在监听");
                    while (true)
                    {
                        //获取一个客户端请求为止
                        HttpListenerContext context = listener.GetContext();
                        //将其处理过程放入线程池
                        System.Threading.ThreadPool.QueueUserWorkItem(ProcessHttpClient, context);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    listener.Stop(); //关闭HttpListener
                }
            }
        }
        //客户请求处理
        void ProcessHttpClient(object obj)
        {
            HttpListenerContext context = obj as HttpListenerContext;
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
            //请求资源路径
            string page = context.Request.Url.LocalPath.Replace("/", "\\");
            string res = string.Format("{0}{1}", basePath, page);
            String query = context.Request.Url.Query.Replace("?", "");
            Console.WriteLine("接收到请求:{0}?{1}", page, query);
            StreamWriter sw = new StreamWriter(context.Response.OutputStream);
            string result = string.Empty;
            if (page == "\\")
            {
                result = File.ReadAllText(@"E:\Html5\UIKit\index.html");
            }
            else
            {
                if (File.Exists(res))
                {
                    result = File.ReadAllText(res);
                }
            }
            sw.Write(result);
            sw.Flush();
            context.Response.OutputStream.Close();
            ////do something as you want
            //string responseString = string.Format(" {0}", DateTime.Now);
            //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            //response.ContentLength64 = buffer.Length;
            //System.IO.Stream output = response.OutputStream;
            //output.Write(buffer, 0, buffer.Length);
            ////关闭输出流,释放相应资源
            //output.Close();
        }
        //异步
        HttpListener listener;
        public bool Running
        {
            get { return listener != null; }
        }
        void Start()
        {
            if (Running)
                return;
            listener = new HttpListener();
            //这里开启Http 监听
            listener.Prefixes.Add("http://192.168.1.117:9988/");//也支持域名形式
            listener.Start();
            //异步等待URL请求传入
            listener.BeginGetContext(EndGetRequest, listener); ;
        }
        void Stop()
        {
            if (!Running)
                return;
            listener.Close();
            listener = null;
        }
        void EndGetRequest(IAsyncResult result)
        {
            HttpListenerContext context = null;
            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;
            try
            {
                context = listener.EndGetContext(result);
                HandleRequest(context);
            }
            catch (Exception ex)
            {
               Console.Write("Exception in listener: {0}{1}", Environment.NewLine, ex);
            }
            finally
            {
                if (context != null)
                    context.Response.Close();
                if (listener.IsListening)
                    listener.BeginGetContext(EndGetRequest, listener);
            }
        }
        void HandleRequest(HttpListenerContext context)
        {
            bool isScrape = context.Request.RawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase);
            //string responseStr = "very nice! haha"n来个中文你支持吗?"n";
            //for (int i = 0; i < context.Request.QueryString.Count; i++)
            //{
            //    responseStr = responseStr + "query:" + context.Request.QueryString.Keys[i] + "=" + context.Request.QueryString[i] + ""n";
            //}
            //Console.WriteLine("good");
            //byte[] response = System.Text.Encoding.Default.GetBytes(responseStr);
            //context.Response.ContentType = "text/plain"; //这里的类型随便你写.如果想返回HTML格式使用text/html
            //context.Response.StatusCode = 200;
            //context.Response.ContentLength64 = response.LongLength;
            //context.Response.OutputStream.Write(response, 0, response.Length);
            //请求资源路径
            string page = context.Request.Url.LocalPath.Replace("/", "\\");
            string res = string.Format("{0}{1}", basePath, page);
            String query = context.Request.Url.Query.Replace("?", "");
            Console.WriteLine("接收到请求:{0}?{1}", res, query);
            StreamWriter sw = new StreamWriter(context.Response.OutputStream);
            string result = string.Empty;
            if (page == "\\")
            {
                result = File.ReadAllText(@"E:\Html5\UIKit\index.html");
            }
            else
            {
                if (File.Exists(res))
                {
                    result = File.ReadAllText(res);
                }
            }
            Console.WriteLine(result);
            sw.Write(result);
            sw.Flush();
            context.Response.Close();
        }
    }
}


知识共享许可协议
《自定义服务器,并宿主在 WPF 程序中》常伟华 创作。
采用 知识共享 署名-相同方式共享 3.0 中国大陆 许可协议进行许可。
相邻依据:发表时间
  • 多说评论
  • 签名
  • 新浪微博
  • 默认评论
  • Tab Header 5

0 条评论 / 点击此处发表评论

Tab Content 5

开发技术


开发平台和工具

sitemap     163.52ms