Android,快速推送消息到1000台设备

发布于 2024-12-25 20:42:19 字数 5193 浏览 1 评论 0原文

我已经实现了 c2dm,并且设备接收消息和所有内容都工作正常。 然而,有一个问题我找不到解决方案。

当某个事件发生时,我想快速将相同的消息推送到数千台设备,最好在一分钟内。我知道该消息是否会被送达并不确定,并且 Google 可能会因不同情况而延迟消息的发送。

我的 iOS 实现大致相同,当然除了发送部分。 15000 条消息大约需要 5 秒。对于向 Android 发送 5000 条消息,需要一个多小时,这太长了。

有谁知道有什么方法可以加快速度吗? 或者谷歌会停止这种大规模的垃圾邮件推送吗?

C2DM部分代码如下。这是用 PHP 编写的,但我阅读大多数其他编程语言都没有问题。 我使用脚本 connect() 一次,然后循环所有令牌并使用 sendMessage() 发送每条消息。所有消息发送完毕后,断开连接()。

<?php
class C2DMclient
{
    private $authKey = NULL;
    private $ch = NULL;

    function connect() {
        $post_params = array(
            'Email'       => 'C2DM_USER',
            'Passwd'      => 'C2DM_PWD',
            'accountType' => 'HOSTED_OR_GOOGLE',
            'source'      => 'appname',
            'service'     => 'ac2dm',
        );
        $first = true;
        $data_msg = '';

        foreach($post_params as $key => $value) {
            if($first)
                $first = false;
            else
                $data_msg .= '&';

            $data_msg .= urlencode($key).'='.urlencode($value);
        }

        $x = curl_init('C2DM_CLIENTLOGIN');
        curl_setopt($x, CURLOPT_HEADER, true);
        curl_setopt($x, CURLOPT_POST, true);
        curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
        curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($x);
        curl_close($x);

        $pos = strpos($response, 'Auth=');
        $this->authKey = trim(substr($response, 5 + $pos));
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_URL, 'C2DM_SERVER');
    }

    function disconnect() {
        curl_close($this->ch);
        $this->authKey = NULL;
    }

    function sendMessage($deviceToken, $message) {
        $data = array(
            'registration_id' => $deviceToken,
            'collapse_key'    => 'ck_type',
            'data.type'       => 'TYPE',
            'data.message'    => $message,
            'data.title'      => 'Title'
        );
        $headers = array('Authorization: GoogleLogin auth='.$this->authKey);

        if($headers)
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($this->ch, CURLOPT_POST, true);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);

        $messagedata = curl_exec($this->ch);
            return TRUE;
    }
}
?>

编辑: 新的解决方案基于curl_multi_exec。

Curl 句柄是在循环访问数据库查询结果时收集的。收集数百个curl句柄后,调用sendMessages($chs)来发送所有这些消息。目前,我在发送前收集了 700 条消息,并且似乎具有良好的传送率并且足够快,约 10 秒即可发送 5000 条消息。较高的数字似乎会影响交付率。

<?php
class C2DMclient
{
    private $authKey = NULL;
    private $ch = NULL;

    function connect() {
        $post_params = array(
            'Email'       => 'C2DM_USER',
            'Passwd'      => 'C2DM_PWD',
            'accountType' => 'HOSTED_OR_GOOGLE',
            'source'      => 'appname',
            'service'     => 'ac2dm',
        );
        $first = true;
        $data_msg = '';

        foreach($post_params as $key => $value) {
            if($first)
                $first = false;
            else
                $data_msg .= '&';

            $data_msg .= urlencode($key).'='.urlencode($value);
        }

        $x = curl_init('C2DM_CLIENTLOGIN');
        curl_setopt($x, CURLOPT_HEADER, true);
        curl_setopt($x, CURLOPT_POST, true);
        curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
        curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($x);
        curl_close($x);

        $pos = strpos($response, 'Auth=');
        $this->authKey = trim(substr($response, 5 + $pos));
    }

    function getMessageCurlHandle($deviceToken, $message) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'C2DM_SERVER');
        $data = array(
            'registration_id' => $deviceToken,
            'collapse_key'    => 'ck_type',
            'data.type'       => 'TYPE',
            'data.message'    => $message,
            'data.title'      => 'Title'
        );
        $headers = array('Authorization: GoogleLogin auth='.$this->authKey);

        if($headers)
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        return $ch;
    }

    function sendMessages($chs) {
        $mh = curl_multi_init();
        foreach($chs as $ch) {
            curl_multi_add_handle($mh, $ch);
        }
        $active = null;
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while($mrc == CURLM_CALL_MULTI_PERFORM);

        while($active && $mrc == CURLM_OK) {
            if(curl_multi_select($mh) != -1) {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }
        curl_multi_close($mh);
    }
}
?>

I have implemented c2dm and it works fine that the device receives the message and everything.
There is however one problem that I can't find a solution for.

When a certain event occurs I want to push the same message to a few thousand devices quickly, preferably within a minute. I know that there is no certainty that the message will ever be delivered and that Google may delay the message due to different circumstances.

My implementation for iOS is about the same except of course the sending part. That takes about 5 sec for 15000 messages. For 5000 messages to Android it takes over an hour which is way to long.

Does anyone know a way to speed this up?
Or does Google stop this kind of mass push to stop spam?

The C2DM part of the code is below. This is in PHP but I have no problem reading most other programming languages.
I use a script to connect() once and then loop all tokens and use sendMessage() to send each message. After all messages is sent, it disconnect().

<?php
class C2DMclient
{
    private $authKey = NULL;
    private $ch = NULL;

    function connect() {
        $post_params = array(
            'Email'       => 'C2DM_USER',
            'Passwd'      => 'C2DM_PWD',
            'accountType' => 'HOSTED_OR_GOOGLE',
            'source'      => 'appname',
            'service'     => 'ac2dm',
        );
        $first = true;
        $data_msg = '';

        foreach($post_params as $key => $value) {
            if($first)
                $first = false;
            else
                $data_msg .= '&';

            $data_msg .= urlencode($key).'='.urlencode($value);
        }

        $x = curl_init('C2DM_CLIENTLOGIN');
        curl_setopt($x, CURLOPT_HEADER, true);
        curl_setopt($x, CURLOPT_POST, true);
        curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
        curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($x);
        curl_close($x);

        $pos = strpos($response, 'Auth=');
        $this->authKey = trim(substr($response, 5 + $pos));
        $this->ch = curl_init();
        curl_setopt($this->ch, CURLOPT_URL, 'C2DM_SERVER');
    }

    function disconnect() {
        curl_close($this->ch);
        $this->authKey = NULL;
    }

    function sendMessage($deviceToken, $message) {
        $data = array(
            'registration_id' => $deviceToken,
            'collapse_key'    => 'ck_type',
            'data.type'       => 'TYPE',
            'data.message'    => $message,
            'data.title'      => 'Title'
        );
        $headers = array('Authorization: GoogleLogin auth='.$this->authKey);

        if($headers)
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($this->ch, CURLOPT_POST, true);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data);

        $messagedata = curl_exec($this->ch);
            return TRUE;
    }
}
?>

EDIT:
New solution is based on curl_multi_exec.

Curl handles are collected while looping through the database query results. After a few hundred curl handles are gathered, sendMessages($chs) are called to send all those messages. At the moment I collect 700 messages before sending and seems to have a good delivery rate and fast enough, ~10s to send 5000 messages. A higher number seem to affect delivery rate.

<?php
class C2DMclient
{
    private $authKey = NULL;
    private $ch = NULL;

    function connect() {
        $post_params = array(
            'Email'       => 'C2DM_USER',
            'Passwd'      => 'C2DM_PWD',
            'accountType' => 'HOSTED_OR_GOOGLE',
            'source'      => 'appname',
            'service'     => 'ac2dm',
        );
        $first = true;
        $data_msg = '';

        foreach($post_params as $key => $value) {
            if($first)
                $first = false;
            else
                $data_msg .= '&';

            $data_msg .= urlencode($key).'='.urlencode($value);
        }

        $x = curl_init('C2DM_CLIENTLOGIN');
        curl_setopt($x, CURLOPT_HEADER, true);
        curl_setopt($x, CURLOPT_POST, true);
        curl_setopt($x, CURLOPT_POSTFIELDS, $data_msg);
        curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($x);
        curl_close($x);

        $pos = strpos($response, 'Auth=');
        $this->authKey = trim(substr($response, 5 + $pos));
    }

    function getMessageCurlHandle($deviceToken, $message) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'C2DM_SERVER');
        $data = array(
            'registration_id' => $deviceToken,
            'collapse_key'    => 'ck_type',
            'data.type'       => 'TYPE',
            'data.message'    => $message,
            'data.title'      => 'Title'
        );
        $headers = array('Authorization: GoogleLogin auth='.$this->authKey);

        if($headers)
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        return $ch;
    }

    function sendMessages($chs) {
        $mh = curl_multi_init();
        foreach($chs as $ch) {
            curl_multi_add_handle($mh, $ch);
        }
        $active = null;
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while($mrc == CURLM_CALL_MULTI_PERFORM);

        while($active && $mrc == CURLM_OK) {
            if(curl_multi_select($mh) != -1) {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                } while($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }
        curl_multi_close($mh);
    }
}
?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

澜川若宁 2025-01-01 20:42:19

[更新] C2DM 现已弃用。它的后继者 Google Cloud Messaging (GCM) 支持 多个接收者 又名批量发送:

{ "data": {
  "score": "5x1",
  "time": "15:10"
  },
  "registration_ids": ["4", "8", "15", "16", "23", "42"]
}

[/Update]

C2DM 尚不支持批量发送。

但是您可以同时向 C2DM 服务器发送多个 POST 请求,
不幸的是 PHP 本身不支持多线程。

看看 curl_multi_exec 它提供了制作多个 cURL 的可能性同时请求。

[Update] C2DM is now deprecated. It's successor Google Cloud Messaging (GCM) supports multiple receivers aka batch sending:

{ "data": {
  "score": "5x1",
  "time": "15:10"
  },
  "registration_ids": ["4", "8", "15", "16", "23", "42"]
}

[/Update]

C2DM doesn't support batch sending yet.

However you could send several POST request to the C2DM server at the same time,
unfortunately PHP has itself no support for multi-threading.

Have a look at curl_multi_exec which gives the possiblity to make several cURL requests at the same time.

温柔戏命师 2025-01-01 20:42:19

另外我会调查 Firebase,我最近经常使用它们,而且看起来非常快。他们拥有适用于相当广泛的框架的 API。他们的目标是非常快速地将更改推送到数据集(消息就是一个完美的例子),因此当发生更改时,他们会向所有连接的用户发送通知消息。

https://www.firebase.com/

Also I would investigate Firebase, I've been playing with them quite a bit lately, and it seems really quick. They have API's for a pretty wide range of frameworks. Their goal is to push changes to datasets (messages are a perfect example) very quickly, so when a change happens they send a notification message out to all connected users.

https://www.firebase.com/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文