Winform开启一个http服务,web服务


winform启动时希望启动一个http服务,做一些简单的API数据和界面交互,有时候一个很小的数据交互,没必要再搞一个IIS,直接在winform中开启一个http服务,模拟开启一个web api后台,供第三方调用

C# 全选
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace ClientDemo
{
    public class HttpService
    {
        private static HttpService _instance;
        public static HttpService Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new HttpService();
                }
                return _instance;
            }
        }

        private System.Net.HttpListener _listener = null;

        public bool startSta = false;

        /// <summary>
        /// 启动
        /// </summary>
        public void Start(string ip, int port)
        {
            Stop();


            List<string> httpPrefixes = new List<string>();
            httpPrefixes.Add("http://" + ip + ":" + port + "/" + "execute/");
            httpPrefixes.Add("http://" + ip + ":" + port + "/" + "check/");
            new Thread(new ThreadStart(delegate
            {
                _listener = new HttpListener();
                while (true)
                {
                    try
                    {
                        _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                        //_listener.Prefixes.Add(httpPrefixes0);
                        //_listener.Prefixes.Add(httpPrefixes1);
                        if (httpPrefixes != null)
                        {
                            foreach (string url in httpPrefixes)
                            {
                                _listener.Prefixes.Add(url);
                            }
                        }
                        _listener.Start();

                    }
                    catch (Exception ex)
                    {
                        startSta = false;
                        break;
                    }

                    //线程池
                    int minThreadNum;
                    int portThreadNum;
                    int maxThreadNum;
                    ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
                    ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
                    //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);
                    try
                    {
                        while (true)
                        {
                            startSta = true;
                            //等待请求连接
                            //没有请求则GetContext处于阻塞状态
                            HttpListenerContext ctx = _listener.GetContext();

                            ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);
                        }
                    }
                    catch
                    {
                        startSta = false;
                    }
                }
            })).Start();
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            if (_listener != null)
            {
                _listener.Stop();
                _listener.Close();
                _listener = null;
            }
        }

        /// <summary>
        /// 任务进
        /// </summary>
        /// <param name="obj"></param>
        void TaskProc(object obj)
        {
            HttpListenerContext ctx = (HttpListenerContext)obj;
            try
            {
                var url = ctx.Request.Url.AbsoluteUri;

                if ("/check".Equals(ctx.Request.Url.AbsolutePath, StringComparison.OrdinalIgnoreCase))
                {
                    ctx.Response.StatusCode = 200;
                    var data = new
                    {
                        status = 0,
                        message = "客户端已启动"
                    };
                    var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                    var bytes = System.Text.Encoding.UTF8.GetBytes(jsonStr);
                    ctx.Response.ContentType = "application/json";
                    ctx.Response.OutputStream.Write(bytes, 0, bytes.Length);
                }
                if ("/execute".Equals(ctx.Request.Url.AbsolutePath, StringComparison.OrdinalIgnoreCase))
                {
                    string command = ctx.Request.Url.GetQuery("command");
                    switch (command)
                    {
                        case "openform1":
                            {

                            };
                            break;
                        case "openform2":
                            {
                            };
                            break;
                    }

                    //Stream stream = ctx.Request.InputStream;
                    //System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
                    //#region 
                    //string body = reader.ReadToEnd();
                    ////这里的body就是客户端发过来的数据
                    //var upRecord = Newtonsoft.Json.JsonConvert.DeserializeObject<UpEventRecord>(body);
                    //if (upRecord != null)
                    //{
                    //    Form1._Instance.InsertRecord(upRecord);
                    //}
                    //#endregion 

                    //stream.Close();
                }

                ctx.Response.Close();
                ctx = null;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.ToString());
            }
        }
    }

    public static class Extensions
    {
        public static string GetQuery(this System.Uri url, string name)
        {
            //url.Query 
            Regex reg = new Regex(name + "=(\\w+)", RegexOptions.IgnoreCase);
            var m = reg.Match(url.Query);
            if (m.Success)
            {
                return m.Groups[1].Value;
            }
            else
                return "";
        }
    }
}
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
张国生
上一篇:白象食品是怎么样的一个企业
下一篇:C# web页面唤醒本地winform应用并执行指定命令
评论列表

发表评论

评论内容
昵称:
关联文章

Winform开启一个http服务,web服务
windows平台的分布式微服务解决方案(5)--Web服务/WebApi的负载均衡
SUSE开启SSH
.NET中大型项目开发必备(5)--Web服务/WebApi的负载均衡
Winform项目和Web API的.NetCore项目中使用Serilog 来记录日志信息
C# web页面唤醒本地winform应用并执行指定命令
GZUpdate自动升级服务 .NET C/S Winform客户端程序自动升级演示
nginx配置http自动重定向到https
YESWin winform开发框架 新建一个业务模块项目
慎用System.Web.HttpContext.Current
YES-WEB快速开发框架,.NET WEB开发平台,高效的web项目开发框架
Winform中使用HttpClient与后端api服务进行交互
nginx反向代理https
CentOS7部署OpenVPN服务
.NET中大型项目开发必备(9)--http请求调用(Post与Get)
windows下openssl安装,证书生成,nginx配置https以及http重定向https
使用.NET 6开发TodoList应用(10)——实现DELETE请求以及HTTP请求幂等性
2.客户端与服务端连接
Winform开发的快速、健壮、解耦的几点建议
ABP VNext框架中Winform终端的开发和客户端授权信息的处理

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码