0

我正在使用一个for循环,其中WebclientDownloadstring()方法用于加载外部 url 。Url 由 SMS 服务提供商提供,其中添加了手机号码和要传输的消息。
但是对于数组中指定的所有手机号码,消息并未提交到 SMS 网关,phNos[]即某些号码的下载 Url 被跳过。这主要发生在数组末尾的手机号码上。

如何确保程序等待直到为特定数字加载 url,然后程序继续前进。

WebClient cli = new WebClient();
for (i=0;i<phNos.Length;i++)
{
    string url = @"http://example.com?DestNo=" + phNos[i] + "&msg=" + message; 
    cli.DownloadString(url);  
}

或者我也使用过 System.Net.HttpWebRequest,但问题仍然存在。

  for (i=0;i<phNos.Length;i++)
    {
        string url = @"http://example.com?DestNo=" + phNos[i] + "&msg=" + message; 
        Uri targetUri = new Uri(url);
        HttpWebRequest hwb = (HttpWebRequest)HttpWebRequest.Create(targetUri);

        System.Net.HttpWebResponse response = hwb1.GetResponse();
        int status = (int)response.StatusCode;

        if (status == 200)
        {

            Response.Write("Successfully transmitted" + status);
        }
    }

是否有任何其他替代方法可以确保消息 100% 提交。

4

2 回答 2

1

我会为每个调用实例化一个 webclient 并在调用 downloadstring 后处理它,就像这样

foreach(var phone in phNos)
{
  using(WebClient cli= new WebClient())
  {
     url = String.Format(@"http://aaa.bbb.ccc.ddd?DestNo={0}&msg={1}", phone, message); 
     string result = cli.DownloadString(url); 
     // check if result has somekind of errorreport maybe? 
     Trace.WriteLine(result);  // optionally write it to a trace file
  }
}

明确处理它可能有助于更快地关闭底层网络连接,因为我怀疑连接的绝对数量会导致问题。节流也可能是一种选择(每分钟向网关发送更少的呼叫)

如果这是 10000 或 100000 次呼叫,您和短信网关之间的网络组件可能是罪魁祸首。想想 adsl 调制解调器/vpn 软件/路由问题,甚至是 sms 网关本身。

如果仍然不能解决问题:尝试Fiddler和/或Wireshark深入检查 http 流量甚至 tcp/ip 流量。

于 2013-02-16T09:18:09.713 回答
1

你的代码看起来不错。DownloadString 被阻塞,如果发生错误,它应该引发异常。SMS网关如何响应您的请求?您应该查看他们的文档,因为您可能可以编写一个函数来测试一切是否正常。

const int MAX_RETRY = 10;
WebClient cli= new WebClient();

for(i=0;i<phNos.Length;i++)
{
    url = @"http://aaa.bbb.ccc.ddd?DestNo=" + phNos[i] + "&msg=" + message;

    int cntRetry = 0;

    while (!TestResult(cli.DownloadString(url)) && cntRetry < MAX_RETRY)
        ++cntRetry;
}

问题可能是您在很短的时间内向网关提交了太多请求。您可以尝试在某处放置一些Thread.Sleep(1000)调用,看看情况是否会好转。

WebClient cli= new WebClient();
for(i=0;i<phNos.Length;i++)
{
    Thread.Sleep(1000);
    url = @"http://aaa.bbb.ccc.ddd?DestNo=" + phNos[i] + "&msg=" + message; 
    cli.DownloadString(url);  
}

您还可以结合上述两个示例,使用可能较低的MAX_RETRYThread.Sleep值。

const int MAX_RETRY = 5;
WebClient cli= new WebClient();

for(i=0;i<phNos.Length;i++)
{
    url = @"http://aaa.bbb.ccc.ddd?DestNo=" + phNos[i] + "&msg=" + message;

    int cntRetry = 0;

    while (!TestResult(cli.DownloadString(url)) && cntRetry < MAX_RETRY) {
        Thread.Sleep(500);
        ++cntRetry;
    }
}
于 2013-02-16T09:26:31.167 回答