Php curl 保持活动连接

Php curl keep alive connection

根据 : https://help.nexmo.com/hc/en-us/articles/205065817-Can-I-send-multiple-SMS-in-a-single-API-request-

"Make sure to keep your connection alive so you can reuse the HTTP socket when sending requests and taking full advantage of your account throughput (5 SMS/second). The best-practice is to leverage HTTP 1/1 and Keep-Alive the connection so each time you are sending a new request you don't need to open another HTTP connection."

我已经阅读了一些信息来尝试使用 curl 保持连接,但我无法发送 5 条短信来重用 http 套接字。

解决方法是什么?

我试过:

curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

没有成功。

我试图删除:

curl_close($ch);

也没有成功...

我找不到保持连接的好方法,以便按照 nexmo 的要求发送短信。

谁知道如何进行?

发送多条消息和使用 keep-alive 是两个不同的事情。使用 Nexmo(如常见问题解答所述),您只能为每个 HTTP 请求发送一条 SMS。要发送多条 SMS,您只需发出多个 HTTP 请求。

默认情况下,Nexmo 将允许您的帐户每秒向 SMS API 发出 5 次请求。如果你想最大化你的吞吐量,你需要确保你尽可能快地发出请求(或者实际上,至少在 5/秒的速率限制下尽可能快)。

这就是 keep-alive 发挥作用的地方,确保您尽快发送请求。 curl_setop 文档引用了一个 CURLOPT_FORBID_REUSE,它允许:

TRUE to force the connection to explicitly close when it has finished processing, and not be pooled for reuse.

所以默认情况下,curl 会尝试使用 keep-alive,假设您重复使用 curl 句柄。有关详细信息,请参阅 this question

quickstarts here 借用此代码(披露,我是这些代码的作者):

<?php
$url = 'https://rest.nexmo.com/sms/json?' . http_build_query([
    'api_key' => API_KEY,
    'api_secret' => API_SECRET,
    'to' => YOUR_NUMBER,
    'from' => NEXMO_NUMBER,
    'text' => 'Hello from Nexmo'
]);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

如果您使用 curl_setop() 设置具有不同编号/消息的新 CURLOPT_URL(重复使用 curl 句柄)curl 应该默认使用 keep-alive

但请记住,这不会改变 如何使用 Nexmo 发送多条消息,这只是优化 的一种方式发送消息的速度