c# HttpListener 实现小型的web服务器 POST GET

c# HttpListener 实现小型的web服务器 POST GET

一、演示

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace server
{
    public partial class FrmMain : Form
    {
        public static string _listenerUri = ConfigurationManager.AppSettings["HttpIP"];
        public HttpListener _listener;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void ListenerHandle(IAsyncResult result)
        {

            try
            {

                if (_listener.IsListening)
                {
                    _listener.BeginGetContext(ListenerHandle, result); // 继续监听

                    HttpListenerContext context = _listener.EndGetContext(result);
                    // 解析Request请求
                    HttpListenerRequest request = context.Request;
                    string content = "";

                    txtLine.BeginInvoke(new Action(() => { txtLine.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "request.Url:" + request.Url + Environment.NewLine); }));

                    switch (request.HttpMethod)
                    {

                        case "POST":
                            {

                                Stream stream = context.Request.InputStream;
                                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                                content = reader.ReadToEnd();
                            }
                            break;

                        case "GET":
                            {
                                NameValueCollection myCol = new NameValueCollection();
                                myCol = request.QueryString;

                                //content = myCol.GetKey(0) + myCol.Get(0);

                                foreach (String str in myCol.AllKeys)
                                {
                                    content = content + " " + str + myCol[str];
                                }

                            }
                            break;
                    }

                    txtLine.BeginInvoke(new Action(() => { txtLine.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "收到数据:" + content + Environment.NewLine); }));

                    // 构造Response响应
                    HttpListenerResponse response = context.Response;
                    response.StatusCode = 200;
                    response.ContentType = "application/json;charset=UTF-8";
                    response.ContentEncoding = Encoding.UTF8;
                    response.AppendHeader("Content-Type", "application/json;charset=UTF-8");

                    using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8))
                    {

                        writer.Write("welcome");
                        writer.Close();
                        response.Close();
                    }
                }

            }
            catch (Exception ex)
            {
                txtLine.BeginInvoke(new Action(() => { txtLine.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ex.ToString() + Environment.NewLine); }));
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            txtHttpIP.Text = _listenerUri;
        }

        /// <summary>
        /// 启用 HTTP请求监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            _listener = new HttpListener();
            _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            _listener.Prefixes.Add(_listenerUri);
            _listener.Start();

            txtLine.AppendText("启用数据监听!" + Environment.NewLine);

            _listener.BeginGetContext(ListenerHandle, _listener);

            btnStart.Enabled = false;
            btnStop.Enabled = true;
        }

        /// <summary>
        /// 停止 HTTP请求监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_listener != null)
            {

                _listener.Close();

                txtLine.AppendText("停止数据监听!" + Environment.NewLine);

                btnStart.Enabled = true;
                btnStop.Enabled = false;
            }
        }
    }
}

二、根据请求判断处理【2022-03-21更新】

浏览器访问http://10.251.251.5/sync?billno=ck202202211001&itemno=1

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace server
{
    public partial class FrmMain : Form
    {
        public static string _listenerUri = ConfigurationManager.AppSettings["HttpIP"];
        public HttpListener _listener;

        public FrmMain()
        {
            InitializeComponent();
        }

        private void ListenerHandle(IAsyncResult result)
        {

            try
            {

                if (_listener.IsListening)
                {
                    _listener.BeginGetContext(ListenerHandle, result); // 继续监听

                    HttpListenerContext context = _listener.EndGetContext(result);
                    // 解析Request请求
                    HttpListenerRequest request = context.Request;
                    string content = "";

                    //txtLine.BeginInvoke(new Action(() => { txtLine.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "request.Url:" + request.Url + Environment.NewLine); }));

                    // 获取请求类型"POST","GET" 等等 (此处转成小写字母)
                    var httpMethod = request.HttpMethod.ToLower();
                    // 查询 "域名/IP" 与 "?" 之间的内容
                    var actionName = request.Url?.AbsolutePath;
                    // 查询地址中"?"后面的键值对
                    var queryString = request.QueryString;

                    switch (actionName)
                    {
                        case "/sync":
                            {
                                /*
                                NameValueCollection myCol = new NameValueCollection();
                                myCol = queryString;

                                //content = myCol.GetKey(0) + myCol.Get(0);

                                foreach (String str in myCol.AllKeys)
                                {
                                    content = content + " " + str + myCol[str];
                                }
                                */

                                string billno = queryString.Get("billno");
                                string itemno = queryString.Get("itemno");

                                content = content + " billno=" + queryString.Get("billno")
                                                  + " itemno=" + queryString.Get("itemno");
                            }
                            break;

                        case "/tran":
                            {

                            }
                            break;

                    }

                    /*
                    switch (httpMethod)
                    {

                        case "POST":
                            {

                                Stream stream = context.Request.InputStream;
                                StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                                content = reader.ReadToEnd();
                            }
                            break;

                        case "GET":
                            {
                                NameValueCollection myCol = new NameValueCollection();
                                myCol = request.QueryString;

                                //content = myCol.GetKey(0) + myCol.Get(0);

                                foreach (String str in myCol.AllKeys)
                                {
                                    content = content + " " + str + myCol[str];
                                }

                            }
                            break;
                    }
                    */

                    txtLine.BeginInvoke(new Action(() => { txtLine.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "收到数据:" + content + Environment.NewLine); }));

                    // 构造Response响应
                    HttpListenerResponse response = context.Response;
                    response.StatusCode = 200;
                    response.ContentType = "application/json;charset=UTF-8";
                    response.ContentEncoding = Encoding.UTF8;
                    response.AppendHeader("Content-Type", "application/json;charset=UTF-8");

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

            }
            catch (Exception ex)
            {
                txtLine.BeginInvoke(new Action(() => { txtLine.AppendText(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ex.ToString() + Environment.NewLine); }));
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            txtHttpIP.Text = _listenerUri;
        }

        /// <summary>
        /// 启用 HTTP请求监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            _listener = new HttpListener();
            _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            _listener.Prefixes.Add(_listenerUri);
            _listener.Start();

            txtLine.AppendText("启用数据监听!" + Environment.NewLine);

            _listener.BeginGetContext(ListenerHandle, _listener);

            btnStart.Enabled = false;
            btnStop.Enabled = true;
        }

        /// <summary>
        /// 停止 HTTP请求监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_listener != null)
            {

                _listener.Close();

                txtLine.AppendText("停止数据监听!" + Environment.NewLine);

                btnStart.Enabled = true;
                btnStop.Enabled = false;
            }
        }
    }
}

 

发表回复

您的电子邮箱地址不会被公开。