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.
3
Answers
It looks like you can use socket_get_status after all if you just make a small addition in the package itself.
These two functions are in streamreader class, socket handler is available here.
In connection class you have the socket handler available so you can grab socket status when trying to read data from socket. Below is a slightly modified read function
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
OwlyCodeStreamingBird
, then implement itsconnect
method:You can also make a class based on
OwlyCodeStreamingBird
, which has access to the stream as well. However, you’ll have to keep track of these streams, because it’s a factory method.Looking at the implementation of class
StreamingBird
, you see you can easily create the streamreader instance yourself, with full control over the connection:The
Connection
object stores the socket resource in a public property$connection
: