我正在接收一条字符串消息并将其分解为多个块,以便我可以将其发送到短信服务(因此不会为您分解它)。在我完成我的工作以分解这些消息之后,我尝试遍历生成的数组并执行一个 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);
}
}
}