0

如果字符超过 136,我们希望将消息拆分为多个 (sms) 文本消息。

但我们还想确保第二条消息在第一条消息之后,第三条消息之前到达。

到目前为止,从我们所做的几个测试来看,它似乎是这样工作的,但是为了确保我们仍然想要添加大约 3 秒左右的延迟。

Thread.Sleep正确的方法,还是有其他解决方案而不是添加延迟?

这是代码:

    // Split message to send them as individual text messages
    string[] messages = splitMessage(request["message"], 132);
    for (int i = 0; i < messages.Length; i++)
    {
        HttpWebRequest _wr = (HttpWebRequest)WebRequest.Create(url);

        // Use the CredentialCache so you can attach the authentication to the request
        CredentialCache mycache = new CredentialCache { { new Uri(url), "Basic", new NetworkCredential(_username, _password) } };

        // use Basic Authentication
        _wr.Credentials = mycache;
        _wr.Method = "POST";
        _wr.ContentType = "application/json";
        _wr.Timeout = -1;   // not sure if necessary but it's not harmful

        // _data variable holds the data to be pushed to the server in the request.
        // this piece of data holds the request to send a text message from the application
        string _data = "{\"outboundSMSMessageRequest\":" +
                        "{\"address\": \"" + formatedAddress + "\",\"requestId\": \"" + request["requestId"] + "\"" +
                        ",\"outboundSMSTextMessage\": \"" + messages[i] + "\",\"senderAddress\": \"" + request["sender"] + "\"" +
                        _optional + "}}";

        //get a reference to the request-stream, and write the POST data (_data) to it
        using (var s = new StreamWriter(_wr.GetRequestStream()))
        {
                s.Write(_data);
        }

        //get response-stream, and use a streamReader to read the content
        try
        {
                HttpWebResponse _response = (HttpWebResponse)_wr.GetResponse();
        }
        catch (WebException ex)
        {
                using (StreamWriter file = new StreamWriter(@"D:\WEB\SMS\jsonResponse.txt", true))
                {
                        file.WriteLine("No good");
                }
                // Log exception and throw as for GET example above
                Trace.WriteLine("No good");
                Trace.WriteLine(ex);
        }

        using (Stream s = _wr.GetResponse().GetResponseStream())
        {
                using (StreamReader sr = new StreamReader(s))
                {
                        var jsonData = sr.ReadToEnd();
                        Trace.WriteLine("Server response: " + jsonData);
                        //decode jsonData with javascript serializer

                        using (StreamWriter file = new StreamWriter(@"D:\WEB\SMS\jsonResponse.txt", true))
                        {
                                file.WriteLine("Server response: " + jsonData);
                        }
                }
        }
}
4

1 回答 1

0

我宁愿检查您的 sms sender API 的文档,因为它可能写在那里他们不保证 sms 消息的顺序 - 它们可以有内部队列,并且来自服务器的响应可能意味着它们已经将消息排入队列,并不是说他们已经交付了。在这种情况下,添加 3、5 甚至 10 秒的延迟将无济于事。

于 2014-10-27T16:14:09.400 回答