I am using a composer package owlycode/streaming-bird to call twitter stream API. The stream API opens a socket between your app and twitter, to receive tweets that have a specified keyword. In my case the keyword is 'hello'.
Here is the code using owlycode/streaming-bird package:
<?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";
});
?>
My problem is when this connection is closed by error, I am unable to know that. So I am unable to reconnect with twitter again.
Is there anything in PHP that searches open sockets based on their domain name?
Maybe something like
check_if_socket_open('https://stream.twitter.com/1.1/statuses/firehose.json')
?
Note: I cannot use socket_get_status, because I don't have the socket variable.
There is no way to check socket status, if you've no access to the socket.
If you're searching for a workaround without touching StreamBird's code, then you can make a class based on \OwlyCode\StreamingBird
, then implement its connect
method:
<?php
class MyStreamReader extends \OwlyCode\StreamingBird
{
protected $stream;
protected function connect($timeout = 5, $attempts = 10)
{
return $this->stream = parent::connect($timeout, $attempts);
}
protected function isConnected()
{
return $this->stream && stream_get_meta_data($this->stream)['eof'];
}
}
class MyStreamingBird extends \OwlyCode\StreamingBird
{
public function createStreamReader($method)
{
$oauth = new \OwlyCode\StreamingBird\Oauth($this->consumerKey,
$this->consumerSecret, $this->oauthToken, $this->oauthSecret);
return new MyStreamReader(new \OwlyCode\StreamingBird\Connection(), $oauth, $method);
}
}
$bird = new MyStreamingBird($consumerKey, $consumerSecret, $oauthToken, $oauthSecret);
$reader = $bird->createStreamReader(StreamReader::METHOD_FILTER); // ...
$reader->isConnected();
You can also make a class based on \OwlyCode\StreamingBird
, which has access to the stream as well. However, you'll have to keep track of these streams, because it's a factory method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With