开发者

Something like thread in php

I'm trying to program yahoo messenger robot,now my robot can get messages and answer to them. Yahoo only can send 100 pm at each time I get notific开发者_JAVA技巧ation.

now I wanna answer the each pm. I use while(true){ } to it and answer first pm,then second ,then 3rd and ... . It's so slow ,because I can make only one connection to yahoo by this(I use curlib). how can I send some messages at same time?I think I need something like thread but in php.


you can use pcntl_fork(). http://www.php.net/manual/en/function.pcntl-fork.php

You need pcntl extension and it only works on Unix

If you use curl function you might take a look at curl_multi_init(). http://www.php.net/manual/en/function.curl-multi-init.php


I've wrote a simple function below, which launches URL, and doesn't wait for a result, so like this you can launch many URLs on your own site, it will make your loop fast, and also no need to install any extensions to your server.

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜