Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何通过GCM向1000多个用户发送推送通知_C#_Asp.net_Push Notification_Google Cloud Messaging - Fatal编程技术网

C# 如何通过GCM向1000多个用户发送推送通知

C# 如何通过GCM向1000多个用户发送推送通知,c#,asp.net,push-notification,google-cloud-messaging,C#,Asp.net,Push Notification,Google Cloud Messaging,我正在使用asp.net c#通过GCM向用户发送推送通知。这是我发送通知的代码 string RegArr = string.Empty; RegArr = string.Join("\",\"", RegistrationID); // (RegistrationID) is Array of endpoints string message = "some test message"; string tickerText = "example test GCM"; string

我正在使用asp.net c#通过GCM向用户发送推送通知。这是我发送通知的代码

string RegArr = string.Empty;
RegArr = string.Join("\",\"", RegistrationID);      // (RegistrationID) is Array of endpoints

string message = "some test message";
string tickerText = "example test GCM";
string contentTitle = "content title GCM";
 postData =
"{ \"registration_ids\": [ \"" + RegArr + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";

string response = SendGCMNotification("Api key", postData);
SendGCMNotification函数:-

private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
    {

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        //  CREATE REQUEST
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
        Request.Method = "POST";
        Request.KeepAlive = false;
        Request.ContentType = postDataContentType;
        Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
        Request.ContentLength = byteArray.Length;

        Stream dataStream = Request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
        //
        //  SEND MESSAGE
        try
        {
            WebResponse Response = Request.GetResponse();
            HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
            if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
            {
                var text = "Unauthorized - need new token";
            }
            else if (!ResponseCode.Equals(HttpStatusCode.OK))
            {
                var text = "Response from web service isn't OK";
            }
            StreamReader Reader = new StreamReader(Response.GetResponseStream());
            string responseLine = Reader.ReadToEnd();
            Reader.Close();

            return responseLine;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return "error";
    }
它工作正常,通知正确地发送给1000个用户。但现在我有1000多个用户,我必须向他们发送通知,但在gcm文档中指定,我们可以一次传递1000个注册ID。我可以做什么来向所有用户发送通知?任何帮助都将被告知


您可能会遇到异常,因为您没有设置内容类型。我找到了,并根据你的需要重写了。您还需要安装Json.Net包

public class NotificationManager
    {
        private readonly string AppId;
        private readonly string SenderId;

        public NotificationManager(string appId, string senderId)
        {
            AppId = appId;
            SenderId = senderId;
            //
            // TODO: Add constructor logic here
            //
        }

        public void SendNotification(List<string> deviceRegIds, string tickerText, string contentTitle, string message)
        {
            var skip = 0;
            const int batchSize = 1000;
            while (skip < deviceRegIds.Count)
            {
                try
                {
                    var regIds = deviceRegIds.Skip(skip).Take(batchSize);

                    skip += batchSize;

                    WebRequest wRequest;
                    wRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                    wRequest.Method = "POST";
                    wRequest.ContentType = " application/json;charset=UTF-8";
                    wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
                    wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

                    var postData = JsonConvert.SerializeObject(new
                    {
                        collapse_key = "score_update",
                        time_to_live = 108,
                        delay_while_idle = true,
                        data = new
                        {
                            tickerText,
                            contentTitle,
                            message
                        },
                        registration_ids = regIds
                    });

                    var bytes = Encoding.UTF8.GetBytes(postData);
                    wRequest.ContentLength = bytes.Length;

                    var stream = wRequest.GetRequestStream();
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();

                    var wResponse = wRequest.GetResponse();

                    stream = wResponse.GetResponseStream();

                    var reader = new StreamReader(stream);

                    var response = reader.ReadToEnd();

                    var httpResponse = (HttpWebResponse) wResponse;
                    var status = httpResponse.StatusCode.ToString();

                    reader.Close();
                    stream.Close();
                    wResponse.Close();

                    //TODO check status
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

为什么不拆分并执行2个请求?@VolodymyrBilyachat你的意思是说我拆分数组,然后使用循环执行此操作?没错。因为若这是API的限制,我不认为你们可以用它做任何事情,所以我会在loop@VolodymyrBilyachat事实上,我做的和你说的完全一样,但它不起作用,也许我在代码中做错了什么。谢谢你的回复,我已经传递了内容类型“Request.ContentType=application/json;”。我的问题是通过使用循环解决的。我也尝试过这个解决方案,它工作正常。
 var notificationManager = new NotificationManager("AppId", "SenderId");
 notificationManager.SendNotification(Enumerable.Repeat("test", 1010).ToList(), "tickerText", "contentTitle", "message");