【发布时间】:2011-11-23 14:23:58
【问题描述】:
我正在尝试对 yahoo messenger 机器人进行编程,现在我的机器人可以接收消息并回复它们。 每次我收到通知时,雅虎只能发送 100 pm。
现在我想回答每个下午。我对它使用while(true){ } 并首先回答下午,然后是第二个,然后是第三个和...。
太慢了,因为我只能通过这个连接到雅虎(我使用 curlib)。
我怎样才能同时发送一些消息?我想我需要像线程但在 php 中的东西。
【问题讨论】:
我正在尝试对 yahoo messenger 机器人进行编程,现在我的机器人可以接收消息并回复它们。 每次我收到通知时,雅虎只能发送 100 pm。
现在我想回答每个下午。我对它使用while(true){ } 并首先回答下午,然后是第二个,然后是第三个和...。
太慢了,因为我只能通过这个连接到雅虎(我使用 curlib)。
我怎样才能同时发送一些消息?我想我需要像线程但在 php 中的东西。
【问题讨论】:
您可以使用 pcntl_fork()。 http://www.php.net/manual/en/function.pcntl-fork.php
你需要 pcntl 扩展,它只适用于 Unix
如果你使用 curl 函数,你可以看看 curl_multi_init()。 http://www.php.net/manual/en/function.curl-multi-init.php
【讨论】:
我在下面写了一个简单的函数,它启动 URL,并且不等待结果,所以像这样你可以在自己的网站上启动许多 URL,它会让你的循环速度快,而且无需在您的服务器上安装任何扩展。
function call_url_async($url, $params, $type='POST', $timeout_in_seconds = 1)
{
//call the URL and don't wait for the result - useful to do time-consuming tasks in background
foreach ($params as $key => &$val)
{
if (is_array($val))
$val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
$fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, $timeout_in_seconds);
//if ($fp == FALSE)
// echo "Couldn't open a socket to ".$url." (".$errstr.")<br><br>";
// Data goes in the path for a GET request
if ('GET' == $type)
$parts['path'] .= '?'.$post_string;
$out = "$type ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
// Data goes in the request body for a POST request
if ('POST' == $type && isset($post_string))
$out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
【讨论】: