2

我正在接收一条字符串消息并将其分解为多个块,以便我可以将其发送到短信服务(因此不会为您分解它)。在我完成我的工作以分解这些消息之后,我尝试遍历生成的数组并执行一个 Web 请求。问题是它只适用于第一条消息,然后挂起。不久之后,我收到一条错误消息,提示“连接已意外关闭”。这发生在它第二次尝试 GetResponse(); 我在这里看到了其他一些帖子,它们只是说要关闭并处理响应和请求流。这根本不适合我。这是我的代码当前所在的位置:

private static void Main(string[] args)
{
    var oldMessage = GetFileString();
    Console.WriteLine(string.Format("Old message: {0}", oldMessage.Length));

    var newMessage = UrlPathEncodeString(oldMessage);
    Console.WriteLine(string.Format("New message: {0}", newMessage.Length));

    var brokenUp = SplitByLength(newMessage, 145).ToArray();
    for(var i = 0; i < brokenUp.Count(); i++)
    {
        brokenUp[i] = brokenUp[i].Insert(0, UrlPathEncodeString(string.Format("({0:D2} of {1:D2})", i + 1, brokenUp.Count())));
        Console.WriteLine(string.Format("Appended length: {0}", brokenUp[i].Length));
    }

    System.Net.ServicePointManager.DefaultConnectionLimit = 100;
    foreach (var block in brokenUp)
    {
        Thread.Sleep(1500);
        SendSms((HttpWebRequest)WebRequest.Create("http://172.20.5.214:90/method/sendsms"), block);
    }
    Console.ReadKey();
}

public static void SendSms(HttpWebRequest request, string message)
{
    //build the request
    var url = "http://ipaddress/method/sendsms";
    //var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    var fields = "CellNumber={0}&Message={1}";
    fields = string.Format(fields, "16021234567", message);

    var fieldsBytes = Encoding.UTF8.GetBytes(fields);
    request.ContentLength = fieldsBytes.Length;
    var length = fieldsBytes.Length;

    using (var requestStream = request.GetRequestStream())
    {
        requestStream.Write(fieldsBytes, 0, length);

        using (var response = request.GetResponse())
        {
            using (var responseStream = response.GetResponseStream())
            {
                responseStream.Close();
            }
        }
        requestStream.Close();
    }
}

public static byte[] ReadFully(Stream stream)
{
    var buffer = new byte[32768];
    using (var ms = new MemoryStream())
    {
        while (true)
        {
            int read = stream.Read(buffer, 0, buffer.Length);
            if (read <= 0)
                return ms.ToArray();
            ms.Write(buffer, 0, read);
        }
    }
}
4

1 回答 1

4

response.Close如果您未能下载响应的全部内容,我遇到过似乎挂起的情况。为什么会这样,我不知道,但是在调用request.Abort之前拨打电话Close()可以解决问题。不过,我不希望您会看到这个问题,除非响应的大小可能有数兆字节。

此外,未能在调用之前关闭请求流GetResponse可能会阻止发送所有数据。我建议requestStream.Close在提出请求之前先打电话。但是同样,您的代码第一次可以工作但在随后的请求中不能工作,这似乎很奇怪。

考虑到我建议的更改,您修改的代码将是:

using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(fieldsBytes, 0, length);
}

using (var response = request.GetResponse())
{
    using (var responseStream = response.GetResponseStream())
    {
        // read the response here.
        request.Abort();
        responseStream.Close();
    }
}
于 2012-11-07T01:31:45.527 回答