I have set up a connection to Googles C2DM system. It works - sort of.
When I ask C2DM to "ping" my Android device, it does so sometimes, but far from always. The problem shows itself on the server-side of things.
Usually, the first "ping" (after the server has started) goes through. I get a response immediately after I call the webservice and shortly thereafter the "ping" shows up on my Android device.
However, if I shortly after the first "ping" again tell my server to send a "ping", the webservice call fails. It never manages to call the C2DM and after a while I get a WebException
(C#) saying the following:
The underlying connection was closed: An unexpected error occurred on
a receive.
No other information is there. If I then try to send again, also that call is blocked.
I change nothing in the code, sometimes it manages to call the webservice and sometimes it doesnt. It seems to me there is a "timeout" for calling the Google webservice. If you call it, you need to wait for X seconds before calling again otherwise it just won't return an answer and give the exception. That's just a guess...
Any ideas?
This is the code that executes on send...
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GoogleMessageUrl); // the google url
request.Method = "POST"
request.KeepAlive = false;
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add(RegistrationIdParam, registrationId); // a valid reg id for an android device
postFieldNameValue.Add(CollapseKeyParam, "0");
postFieldNameValue.Add(DelayWhileIdleParam, "0");
postFieldNameValue.Add(DataPayloadParam, message);
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
request.ContentLength = byteArray.Length;
request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + _authTokenString);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
HttpStatusCode responseCode = ((HttpWebResponse)response).StatusCode;
if (responseCode.Equals(HttpStatusCode.Unauthorized) || responseCode.Equals(HttpStatusCode.Forbidden))
{
Console.WriteLine("Unauthorized - need new token");
}
else if (!responseCode.Equals(HttpStatusCode.OK))
{
Console.WriteLine("Response from web service not OK :");
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
}
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseLine = reader.ReadLine();
reader.Close();
response.Close();
return responseLine; // it never gets here, but an Exception is caught else where
Updated
I have found out that this is not a C2DM problem, but some problem with HttpWebRequest
and its GetResponse
, see comments below.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…