HttpListener调用了两次

HttpListener调用了两次

本文介绍了HttpListener调用了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来实现Http Server:

I am using this code to implement Http Server:

public Server()
    {
        _httpListener = new HttpListener();
        _httpListener.Prefixes.Add(Server.UriAddress);
        StartServer();
    }

    public void StartServer()
    {
        _httpListener.Start();

        while (_httpListener.IsListening)
            ProcessRequest();
    }

    void ProcessRequest()
    {
        var result = _httpListener.BeginGetContext(ListenerCallback, _httpListener);
        result.AsyncWaitHandle.WaitOne();
    }

    void ListenerCallback(IAsyncResult result)
    {
        HttpListenerContext context = _httpListener.EndGetContext(result);
        HttpListenerRequest request = context.Request;
        string url = request.RawUrl;
        url = url.Substring(1, url.Length - 1);

        HttpListenerResponse response = context.Response;
        string responseString = url;
        byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
        response.ContentLength64 = buffer.Length;
        System.IO.Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);
        output.Close();
    }

我有一个问题,如果我在浏览器中编写了此代码(这是一个示例,并且每次调用时都会出现):

And i have a problem that if i wrote this in the browser(It's an example and it's occur on every call):

http://localhost:8888/Hello%20World

ListenerCallback 方法被调用了两次,是否知道如何解决?

the ListenerCallback method is called twice,any idea how to fix it?

推荐答案

如果您的网站需要多次调用服务器,它将被多次调用.当您在页面上拥有图片或其他任何内容时,就会发生这种情况.
尝试调用同步方法 _httpListener.GetContext()或将您的调用与 lock Mutex 同步.

If your website requires several calls to the server, it will be called several times. This happens when you hav pictures or anything else on you page.
Try to call the synchronous method _httpListener.GetContext() or synchronize your calls with a lock or Mutex.

这篇关于HttpListener调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:13