我已经使用GCM为Android创建了一个推送通知
该服务正面临许多超时,并且工作时断时续。我有一个Windows服务,它在任意时间(在这种情况下是30秒)运行,并检查消息队列,如果有任何消息存在,它会将其发送到相应的设备。
模式为:
它适用于前两三次,如果一旦失败,它就开始连续失败。
失败的原因是什么?
编辑我认为这可能是由于组织的防火墙造成的,但这也可能被过度统治,因为我在开放网络上尝试过。任何投入,任何思路都会有所帮助提前感谢
代码:
private void SendAndroidMessage(string deviceID,string Message ,DeviceDataModel ddm)
{
StringBuilder postMsgBuilder = new StringBuilder();
postMsgBuilder.Append("registration_id=").Append(deviceID);
//postMsgBuilder.Append("&").Append("delay_while_idle=").Append("false");
postMsgBuilder.Append("&").Append("data.message=").Append(Message);
byte[] messageBytes = Encoding.UTF8.GetBytes(postMsgBuilder.ToString());
var request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
// Hook a callback to verify the remote certificate
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(C2dmCertValidationCallback);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = messageBytes.Length;
request.Headers.Add(HttpRequestHeader.Authorization, "key=" + AuthorisationKey);
bool sent = false;
int tries = 0;
HttpWebResponse response;
while (!sent && tries < this.numOfRetries)
{
try
{
using (var requestStream = request.GetRequestStream())
{
// we are not using retries yet.. or looking for errors here. We should log errors too.
requestStream.Write(messageBytes, 0, messageBytes.Length);
}
// Sends the notification and gets the response.
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.NotFound)
{
return;
}
if (response.StatusCode != HttpStatusCode.OK)
{
tries++;
if (tries > this.numOfRetries)
{
if (this.NotificationFailed != null)
{
this.NotificationFailed(this, new NotificationEventArgs(new NotificationException(string.Format(CultureInfo.InvariantCulture, "{0} notification failures for {1} for DeviceId:{2} of DeviceType:{3}. Giving up", this.numOfRetries, C2dmUrlStr,ddm.DeviceId,ddm.DeviceType))));
}
return;
}
}
else
{
sent = true;
}
}
catch (WebException e)
{
// check why we got the exception
string responseString = "";
if (e.Response != null)
{
StreamReader reader = new StreamReader(e.Response.GetResponseStream());
responseString= reader.ReadToEnd();
}
if (this.NotificationFailed != null)
{
this.NotificationFailed(this, new NotificationEventArgs(new NotificationException("Notification failed with exception " + e.Message + "for " + "https://android.googleapis.com/gcm/send"+" DeviceId: "+ddm.DeviceId+" Device Type: "+ddm.DeviceType+"Response String : "+ responseString, e)));
}
throw;
}
}
}
我也曾遇到过类似的问题,奇怪的是,这是因为我在读取响应流后没有关闭它。在使用response
完成读取后,尝试调用response.Close();
。我希望你也能成功。