C#Http服务器 - 处理多个请求

时间:2015-03-01 14:25:15

标签: c# multithreading httpserver

我正在使用此HttpServer类来处理http请求并在接收多个请求时出现问题。 HttpServer实例是在MainForm上创建的,如果MainForm适用于一些繁重的任务,HttpServer在Main完成这些任务之前不会处理请求。即使HttpServer在另一个线程上侦听和处理请求,它的行为也是如此。

MainForm上的实例创建代码:

HTTPServer httpServer = new HTTPServer("https", "5000");

我也尝试在自己的线程上创建它,但它没有帮助:

(new Thread(() => { new HTTPServer("https", "5000"); })).Start();

HTTPServer类代码:

    public class HTTPServer
    {
    bool listenerStop = false;
    HttpListener listener = new HttpListener();
    string prefixFormat = "{0}://+:{1}/";
    string prefix = "";
    Thread t;

    public HTTPServer(string protocol, string port) {
        string prefix = String.Format(prefixFormat, protocol, port);
        t = new Thread(new ThreadStart(serverThread));
        t.Start();
    }

    public void stopServer() {
        t.Abort();
    }

    public void serverThread() {
        try {
            if (!HttpListener.IsSupported) return;
            listener = new HttpListener();
            listener.Prefixes.Add(prefix);
            listener.Start();
        }
        catch (Exception ex) {
            System.Windows.Forms.MessageBox.Show(ex.Message);
            return;
        }

        while (!listenerStop)
        {
            IAsyncResult result = listener.BeginGetContext(new AsyncCallback(listenerCallback), listener);
            result.AsyncWaitHandle.WaitOne();
        }
        listener.Stop();
    }        

    private void listenerCallback(IAsyncResult result) {
        try
        {
            HttpListener listener = (HttpListener)result.AsyncState;
            HttpListenerContext context = listener.EndGetContext(result);
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            //Do work...
        }
        catch (Exception ex) {
           //Http server error
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的WaitOne将导致serverThread在等待回调完成时阻止。由于回调位于主线程上,这意味着在完成其工作之前,您将被阻止。

重构,这样您就不需要等待语句,就可以消除阻塞问题。