C# 通过HttpListener实现简单的Http服务

 

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using Utils.Networking;

namespace HttpListenerdDemo {
    class Program {

        static HttpServer sSocket = null;

        static void Main(string[] args) {

            sSocket = new HttpServer("http://+:8000/api/test/get/");
            sSocket.OnRequest += GetContextCallBack;
            sSocket.Listen();

            while (true) {
                string text = Console.ReadLine();
                Console.WriteLine($"msg:{text}");
            }

        }

        static void GetContextCallBack(HttpListenerContext context) {
            try {

                var request = context.Request;

                using (var strem = request.InputStream) {
                    using (var reader = new StreamReader(strem, Encoding.UTF8)) {

                        var msg = reader.ReadToEnd();
                        msg = System.Web.HttpUtility.UrlDecode(msg);


                        var data = "";
                        var cardId = msg.get("cardId");

                        if (!cardId.IsEmpty()) {
                            data = new { code = "0", mgs = "成功", name = cardId, balance = 10000 }.Json();
                        } else {
                            data = new { code = "1", mgs = "invalid cardId", name = "", balance = "" }.Json();
                        }

                        using (var response = context.Response) {
                            var buffer = Encoding.UTF8.GetBytes(data);
                            response.ContentLength64 = buffer.Length;

                            using (var output = response.OutputStream) {
                                output.Write(buffer, 0, buffer.Length);
                            }

                        }

                    }

                }

            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }

    }

    public static class Expand {

        public static bool IsEmpty(this string s) {
            return string.IsNullOrWhiteSpace(s);
        }

        public static string Json(this object o) {
            return new JavaScriptSerializer().Serialize(o);
        }

        public static string GetIp {
            get {
                var localIp = "";
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList) { if (ip.AddressFamily.ToString() == "InterNetwork") localIp = ip.ToString(); }
                return localIp;
            }

        }

        public static byte[] Remove(this byte[] b, byte cut = 0x00) {
            var list = new List<byte>();
            list.AddRange(b);
            for (var i = list.Count - 1; i >= 0; i--) {
                if (list[i] == cut) { list.RemoveAt(i); } else { break; }
            }
            var lastbyte = new byte[list.Count];
            for (var i = 0; i < list.Count; i++) {
                lastbyte[i] = list[i];
            }
            return lastbyte;
        }

        public static string get(this string str, string name) { return str.match("\"" + name + @""":""([^""]+)", 1); }

        public static string getmoney(this string str, string name) { return str.match("\"" + name + @""":""?([\-\d\.]+)", 1); }

        public static string match(this string s, string p, int i = 0) {
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(p)) return string.Empty;
            var match = Regex.Match(s, p);
            if (i < match.Groups.Count) return match.Groups[i].Value;
            i = 0;
            return match.Groups[i].Value;
        }

        public static string ToHexStr(this byte[] b) {
            if (b == null) return "";
            var s = string.Join("", b.Select(i => i.ToString("X2")));
            return s;
        }

        public static string Tomd5Str(this string s) { return string.Join("", MD5.Create().ComputeHash(Encoding.Default.GetBytes(s)).Select(v => v.ToString("x2"))); }

        public static byte[] ToBytes(this string s) {
            s = Replace(s, @"[^\dA-Fa-f]+", "");
            if (s.Length % 2 > 0) s = "0" + s;
            var max = s.Length / 2;
            var buf = new byte[max];
            for (var i = 0; i < max; i++) buf[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
            return buf;
        }

        public static string Replace(this string s, string p, string r) {
            return Regex.Replace(s, p, r);
        }

        /// <summary>
        /// 校验
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        public static byte verify(this byte[] buff) {
            int len = buff[2];
            byte sum = 0;
            for (int i = 0; i < len; i++) sum = (byte)(sum + buff[i + 3]);
            return sum;
        }
    }
}

 

 

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

namespace Utils.Networking {
    public class HttpServer : IDisposable {
        public string Prefix { get; set; }

        private readonly HttpListener _listener;

        public delegate void DOnProcessRequest(HttpListenerContext context);
        public event DOnProcessRequest OnRequest;

        private bool _disposed;

        public void Listen() {
            _listener.Start();
            _listener.BeginGetContext(GetContextCallBack, null);
        }

        private void GetContextCallBack(IAsyncResult ar) {
            if (_disposed) return;

            var context = _listener.EndGetContext(ar);
            _listener.BeginGetContext(GetContextCallBack, null);

            OnRequest?.Invoke(context);
        }

        public void Dispose() {
            if (_disposed) return;
            _disposed = true;
            try {
                _listener.Stop();
                _listener.Close();
            } catch (ObjectDisposedException) { }
        }

        public HttpServer(string host, int port) : this() {
            if (string.IsNullOrEmpty(host))
                host = "*";

            Prefix = $"http://{host}:{port}/";
            _listener = new HttpListener();
            _listener.Prefixes.Add(Prefix);
        }

        public HttpServer(int port) : this() {
            Prefix = $"http://*:{port}/";
            _listener = new HttpListener();
            _listener.Prefixes.Add(Prefix);
        }

        public HttpServer(string uri) : this() {
            Prefix = uri;
            _listener = new HttpListener();
            _listener.Prefixes.Add(Prefix);
        }

        public HttpServer() {
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值