HttpWebRequest getRequestStream在多次运行时挂起

时间:2012-10-09 11:38:19

标签: c# httpwebrequest

我编写了一些代码来发送和读取侦听器中的文本。这在第一次和第二次交换时运行良好,但在第三次发送时,调用GetRequestStream和实际写入数据之间存在很长的延迟。

我已经将发送端的流出,流读取器以及读取端的输入流按照此处的建议进行了处理: Does anyone know why I receive an HttpWebRequest Timeout?

它仍然在第3次尝试发送信息时挂起。它肯定似乎挂在sendMessage中的GetRequestStrean:

public void sendMessage(string message)
{
    HttpWebRequest request;
    string sendUrl;

    sendUrl = "http://" + termIPAddress + ":" + sendPort + "/";
    Uri uri = new Uri(sendUrl);
    Console.WriteLine("http://" + termIPAddress + ":" + sendPort + "/");

    ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
    servicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
    servicePoint.ConnectionLeaseTimeout = 300;


    request = (HttpWebRequest)WebRequest.Create(sendUrl);
    request.KeepAlive = false;
    request.Method = "POST";
    request.ProtocolVersion = HttpVersion.Version11;
    request.ContentType = "application/x-www-form-urlencoded";
    request.Headers.Add("SourceIP", localIPAddress);
    request.Headers.Add("MachineName", localName);
    requestStarted = true;


    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message);
    request.ContentLength = buffer.Length;
    try
    {
        using (Stream output = request.GetRequestStream())
        {
            output.Write(buffer, 0, buffer.Length);
            output.Close();
            request = null;
        }
    }
    catch(WebException wE)
    {
        Console.WriteLine(wE.Message);
    }
}

这是阅读部分:

public string getMessage()
{
    Console.WriteLine("Entering actual listener");
    string s;
    string sourceIP;

    NameValueCollection headerList;

    HttpListenerContext context = terminalListener.GetContext();
    HttpListenerRequest request = context.Request;

    headerList = request.Headers;
    sourceIP = headerList.GetValues("SourceIP")[0];
    termName = headerList.GetValues("MachineName")[0];
    termIPAddress = sourceIP;
    using (System.IO.Stream body = request.InputStream)
    {
        System.Text.Encoding encoding = request.ContentEncoding;
        using (System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding))
        {
            s = reader.ReadToEnd();
            body.Close();
            reader.Close();
        }
    }

    return termName + " : " + s;    
}

我也尝试添加IP端点绑定但必须诚实,我不完全理解这段代码:

private IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
    int portNumber = Convert.ToInt32(sendPort);
    IPEndPoint IEP = new IPEndPoint(IPAddress.Parse(localIPAddress), 0); 
    Console.WriteLine(Convert.ToString(IEP));
    return IEP;  
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:11)

您忘记致电HttpWebRequest.GetResponse,因此用完了连接限制。

因此,您应该按如下方式更改代码:

try
{
    using (Stream output = request.GetRequestStream())
        output.Write(buffer, 0, buffer.Length);

    var response = request.GetResponse() as HttpWebResponse;
    //TODO: check response.StatusCode, etc.
}
catch(WebException wE)
{
    Console.WriteLine(wE.Message);
}

此外,在某些情况下,您可能需要调整默认连接限制: ServicePointManager.DefaultConnectionLimit

或者使用持久连接: HttpWebRequest.KeepAlive