| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 | using System;using System.Collections.Generic;using System.Diagnostics;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace LJLib.HttpServer{    public abstract class LJHttpServer    {        private readonly int _port;        TcpListener _listener;        bool is_active = true;        protected LJHttpServer(int port)        {            _port = port;        }        public void Listen()        {            _listener = new TcpListener(IPAddress.Any, _port);            _listener.Start();            ThreadPool.QueueUserWorkItem(state =>            {                // 侦听线程                Thread.CurrentThread.IsBackground = false;                try                {                    while (is_active)                    {                        if (_listener.Pending())                        {                            TcpClient s = _listener.AcceptTcpClient();                            ThreadPool.QueueUserWorkItem(st =>                            {                                try                                {                                    Thread.CurrentThread.IsBackground = true;                                    LJHttpProcessor processor = new LJHttpProcessor(s, this);                                    processor.Process();                                }                                catch (System.Exception e)                                {                                    Trace.Write("HTTP请求处理线程异常退出:" + e.ToString());                                }                            });                        }                        else                        {                            Thread.Sleep(100);                        }                    }                }                catch (System.Exception e)                {                    Trace.Write("HTTP监听异常退出:" + e.ToString());                }            });        }        public void Stop()        {            is_active = false;        }        public abstract void HandleGetRequest(LJHttpProcessor p);        public abstract void HandlePostRequest(LJHttpProcessor p, StreamReader inputData);    }}
 |