如果套接字仍然连接,如果我没有套接字处理程序,如何检入PHP?

时间:2016-04-13 20:47:43

标签: php linux sockets twitter

我正在使用作曲家包owlycode/streaming-bird来致电twitter stream API。流API在您的应用和推特之间打开一个套接字,以接收具有指定关键字的推文。就我而言,关键字是' hello'。

以下是使用owlycode / streaming-bird软件包的代码:

 <?PHP
    $oauthToken = '';
    $oauthSecret = '';
    $consumerKey = '';
    $consumerSecret = '';

    $bird = new StreamingBird($consumerKey, $consumerSecret, $oauthToken, $oauthSecret);

    $bird
        ->createStreamReader(StreamReader::METHOD_FILTER)
        ->setTrack(['hello']) // Fetch every tweet containing one of the following words
        ->consume(function ($tweet) { // Now we provide a callback to execute on every received tweet.
            echo '------------------------' . "\n";
            echo $tweet['text'] . "\n";
        });
  ?>

我的问题是当这个连接被错误关闭时,我无法知道。所以我无法再次与Twitter重新联系。

PHP中是否存在根据域名搜索打开套接字的内容?

也许像

  check_if_socket_open('https://stream.twitter.com/1.1/statuses/firehose.json')

注意:我无法使用socket_get_status,因为我没有套接字变量。

3 个答案:

答案 0 :(得分:4)

如果您无法访问套接字,则无法检查套接字状态。

如果您在不触及StreamBird代码的情况下搜索变通方法,那么您可以根据import pandas # Reads csv file and converts it to pandas dataframe. df = pandas.read_csv('myfile.csv') # Removes rows where data is missing. df.dropna(inplace=True) # Gets length of dataframe and displays it. df_length = df.count + 1 print('The length of the CSV file is', df_length) 创建一个类,然后实现其$("input").click(function() { document.getElementById('partner').innerHTML = "[here I have to put the name / id of the textarea]"; } 方法:

\OwlyCode\StreamingBird

您还可以根据connect创建一个类,该类也可以访问该流。但是,您必须跟踪这些流,因为它是一种工厂方法。

答案 1 :(得分:1)

看起来你可以使用socket_get_status,如果你只是在包本身做一个小的补充。

这两个函数在streamreader类中,套接字处理程序在这里可用。

public function consume(callable $handler)
{
    $this->running = true;
    while ($this->running) { /// while $this->running is true socket will try to reconnect always. 
        $this->consumeOnce($handler);
    }
}
    protected function consumeOnce(callable $handler)
    {
        $this->connection = $this->connect();
        $lastStreamActivity = time();
        $this->connection->read(function ($tweet) use (&$lastStreamActivity, $handler) {
            $idle = (time() - $lastStreamActivity);
            $this->monitor->stat('max_idle_time', $idle);
            $this->monitor->stat('idle_time', $idle);
            $this->monitor->stat('tweets', 1);
            $lastStreamActivity = time();
            call_user_func($handler, $tweet, $this->monitor);
        });
        $this->connection->close();
    }

在连接类中,您可以使用套接字处理程序,以便在尝试从套接字读取数据时获取套接字状态。以下是略有修改的读取功能

public function read(callable $callback, $timeout = 5)
        {
            $this->pool = [$this->connection];
    stream_set_timeout($this->connection, $timeout);
    $info = stream_get_meta_data($this->connection);
            while ($this->connection !== null && !feof($this->connection) && stream_select($this->pool, $fdw, $fde, $timeout) !== false && $info['timed_out']!==true) {
                // @todo safeguard no tweets but connection OK. (reconnect)
                $this->pool = [$this->connection];
                $chunkInfo = trim(fgets($this->connection));
                if (!$chunkInfo) {
                    continue;
                }
                $len = hexdec($chunkInfo) + 2;
                $streamInput = '';
                while (!feof($this->connection)) {
                    $streamInput .= fread($this->connection, $len-strlen($streamInput));
                    if (strlen($streamInput)>=$len) {
                        break;
                    }
                }
                $this->buffer .= substr($streamInput, 0, -2);
                $data = json_decode($this->buffer, true);
                if ($data) {
                    call_user_func($callback, $data);
                    $this->buffer = '';
                }
            }
        }

答案 2 :(得分:1)

查看implementation of class StreamingBird,您会发现自己可以轻松创建流读取器实例,并完全控制连接:

namespace \OwlyCode\StreamingBird;
// Let's instantiate the Oauth signature handler
$oauth = new Oauth($consumerKey, $consumerSecret, $oauthToken, $oauthSecret);
// Let's create our own Connection object!
$connection = new Connection();

// And here comes our Reader
$reader = new StreamReader($connection, $oauth, StreamReader::METHOD_FILTER);
$reader->setTrack(['hello'])
       ->consume(function ($tweet) {
            echo '------------------------' . "\n";
            echo $tweet['text'] . "\n";
       });

// Voilà
print_r(socket_get_status($connection->connection));

Connection object stores the socket resource in a public property $connection

public $connection;
// ... 
@$this->connection = fsockopen($host, $port, $errNo, $errStr, $timeout);