簡體   English   中英

C#Http服務器 - 處理多個請求

[英]C# Http server - handling multiple requests

我正在使用此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
        }
    }
}

WaitOne將導致serverThread在等待回調完成時阻塞。 由於回調在您的主線程上,這意味着您將被阻止,直到它完成其工作。

重構,這樣您就不需要等待語句,您將消除阻塞問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM