Multiple connect using ratchet pawl - ratchet

I need to listen 2 web socket URLs in real-time together. I create 2 connect to different URLs, but I see only the first message results. How can I get messages from wss://exalpme2 without close first connect?
My code example
\Ratchet\Client\connect('wss://exalpme1')->then(function($conn) {
$conn->on('message', function($msg) use ($conn) {
echo "Received: {$msg}\n";
});
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});
\Ratchet\Client\connect('wss://exalpme2')->then(function($conn) {
$conn->on('message', function($msg) use ($conn) {
echo "Received: {$msg}\n";
});
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});

I'm on the ReactPHP core team. It looks like you picked the simple example at the top of the readme. That's fine for when you only open one connection, but in your case you want more than that. At the bottom of the readme is a bit more advanced example but that's overkill for this. Consider the following bit of code that does the following things.
It uses a shared event loop instead of creating one in the helper function
Opens two websocket connections
Shows when errors happen on those connections
Shows when those connections close
Start the event loop
require __DIR__ . '/vendor/autoload.php';
$loop = \React\EventLoop\Factory::create();
$connector = new \Ratchet\Client\Connector($loop);
$connector('wss://exalpme1')->then(function($conn) {
$conn->on('message', function($msg) use ($conn) {
echo "Received: {$msg}\n";
});
$conn->on('error', function(\Throwable $t) {
echo $t;
});
$conn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});
$connector('wss://exalpme1')->then(function($conn) {
$conn->on('message', function($msg) use ($conn) {
echo "Received: {$msg}\n";
});
$conn->on('error', function(\Throwable $t) {
echo $t;
});
$conn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});
$loop->run();

Related

How to get Twilio call status in Laravel?

I have a Laravel app where I have some logic and I'm using Twilio to make the phone call but I want to make when the user missed the phone call after the user will get the SMS and for that, I need to know the call status but how do I get the call status in Laravel. If anybody can help me please feel free to respond.
public function initiateCall(Request $request)
{
// Validate form input
$this->validate($request, [
'phone_number' => 'required|string',
]);
try {
//Lookup phone number to make sure it is valid before initiating call
$phone_number = $this->client->lookups->v1->phoneNumbers($request->phone_number)->fetch();
// If phone number is valid and exists
if ($phone_number) {
// Initiate call and record call
$call = $this->client->account->calls->create(
$request->phone_number, // Destination phone number
$this->from, // Valid Twilio phone number
array(
"record" => True,
"url" => "http://demo.twilio.com/docs/voice.xml"
)
);
if ($call) {
echo 'Call initiated successfully';
} else {
echo 'Call failed!';
}
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
} catch (RestException $rest) {
echo 'Error: ' . $rest->getMessage();
}
}
In the else section of the code when the code echo 'Call failed!'
else {
echo 'Call failed!';
}
you can create or call a function here to send a SMS to user after failed call & also you can set a counter variable here that changes the variable's value to indicate that call is failed.

How do I keep my script streaming so, it doesn't disconnecting?

So, I'm using filtered stream. Unfortunately, every time I turn it on, after 5 minutes its turns off but during that time, it catches tweets.
What I'm trying to do is keep it on 24/7 so, it doesn't turn off after 5 minutes. Also, if it disconnects I want it so, it tries connecting again.
This is the code sample I'm using to help adjust my code:
https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/master/Filtered-Stream/filtered_stream.js
function streamTweets(retryAttempt) {
const stream = needle.get(streamURL, {
headers: {
Authorization: `Bearer ${TOKEN}`
},
retryAttempt: 20000
});
stream.on('data', (data) => {
try {
const json = JSON.parse(data)
console.log(json.data.text)
retryAttempt = 0;
} catch (e) {
if (data.detail === "This stream is currently at the maximum allowed connection limit.") {
console.log(data.detail)
process.exit(1)
} else {
// Keep alive signal received. Do nothing.
}
}
}).on('err', error => {
if (error.code !== 'ECONNRESET') {
console.log(error.code);
process.exit(1);
} else {
// This reconnection logic will attempt to reconnect when a disconnection is detected.
// To avoid rate limits, this logic implements exponential backoff, so the wait time
// will increase if the client cannot reconnect to the stream.
setTimeout(() => {
console.warn("A connection error occurred. Reconnecting...")
streamTweets(++retryAttempt);
}, 2 ** retryAttempt)
}
});
return stream;
}
(async() => {
let currentRules;
try {
//get all stream rules
currentRules = await getRules();
//delete all stream rules
await deleteRules(currentRules);
//Set rules based on array above
await setRules();
} catch (e) {
console.error(e);
process.exit(1);
}
streamTweets(0);
})();
Have you tried to send the keepalive in your header?
Also, I changed the authorization header to match the syntax that of your linked GitHub code source.
function streamTweets(retryAttempt) {
const stream = needle.get(streamURL, {
headers: {
"authorization": `Bearer ${token}`,
"Connection": "keep-alive"
},
retryAttempt: 20000
});
Also, according to the Twitter docs: " If you would like to close your connection, you can press Control-C in your command line tool on either Mac or Windows systems to break the connection, or you can also close the window. "
Are you sure it's not disconnecting because you closed the terminal session, or was closed by something like an ssh timeout?

Run socket Server in a ionic1 application

Here is the requirement:
Start a socket server in the app which will receive messages from another app running in the same device.
Here is the stack:
Ionic1/cordova
Angular1
cordova plugin: https://www.npmjs.com/package/cordova-plugin-chrome-apps-sockets-tcpserver
Using the chrome's tcpServer plugin, I ended this code:
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
var tcpServer = window.chrome && window.chrome.sockets &&
window.chrome.sockets.tcpServer;
if(tcpServer) {
console.log('LOG tcpServer present')
tcpServer.create({}, function (createInfo) {
var serverSocketId = createInfo.socketId;
console.log('LOG', 'serverSocketId', serverSocketId)
if (serverSocketId > 0) {
tcpServer.listen(serverSocketId, '0.0.0.0', 8080, 50, function(resultCode) {
console.log('LOG', 'listening', resultCode)
});
} else {
console.log('LOG', 'Unable to create socket');
}
});
} else {
console.log('LOG', 'missing chrome.sockets.tcpServer')
}
});
})
And the result of this code is:
LOG tcpServer present
LOG serverSocketId 0
LOG Unable to create socket
Given that I've no experience in ionic1/iOS:
Is this my option to create this socket server?
0 means that the create method failed. What could I be doing wrong here?
Do I need some special permission in iOS to perform those actions? (Similar to Android)
I couldn't find resources/examples to help me doing this. Where should I search?
Any help is appreciated

How to get the page Info.totalResults from the youtube api Search: list

Below is the code i have created so far, my goal is to use the youtube Search: list api to find streams for specific games and then publish how many streams there are for that game, I have a database for the game titles and this is my function below, my api link does work im just not able to get the Info.totalResults from it, any help would be great, Thank you for any help you can provide
function totalgamelist() {
global $wpdb;
$gamelistname = $wpdb->prefix . 'Games';
global $wpdb;
$getgames = $wpdb->get_results( 'SELECT * FROM '.$gamelistname , OBJECT );
if (empty($getgames)) {
//empty array
echo 'This is empty sorry!';
} else {
echo 'We Got Something!';
foreach ( $getgames as $getgame )
{
echo '<div class="gamename">'.$getgame->GameTitle;
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=50&q='.$getgame->GameTitle.'&key=[API KEY]");
$json_data = json_decode($JSON, true);
echo $json_data['totalResults'];
echo '</div>';
}
}
}
EDIT:
So with the help from johnh10, i was able to find out that it wasn't my ability to display the results although the echo johnh10 gave is correct :) it was also that my server was blocking access to the url i was asking to view. Below is the curl code i used to access the url, hope it helps others.
$urlgame = 'https://www.googleapis.com/youtube/v3/search?part=snippet&eventType=live&type=video&videoCategoryId=20&regionCode=US&maxResults=1&q='.$getgame->GameTitle.'&key=[API Key]';
$ch = curl_init($urlgame);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$json_data = json_decode($data, true);
if (!empty($json_data)) {
$streamnumber = $json_data['pageInfo']['totalResults'];
echo ' Streams:'.$streamnumber;
} else {
echo ' Streams: No Streams Found';
}
echo $json_data['pageInfo']['totalResults'];

socket.io can't handle errors

I'm trying to make real time application with node.js and socket.io. As I can see the server can see when new user connects but can't return information to client side or something. This is what I've on client side:
<script src="<?= base_url('assets/js/socket.io.js') ?>"></script>
<script>
var socket;
socket = io('http://***.***.***.***:3030', {query: "key=key"});
socket.on('connect', function (data) {
console.log('Client side successfully connected with APP.');
});
socket.on('error', function (err) {
console.log('Error: ' + err);
});
</script>
and this is the server side:
var app = require("express")();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
http.listen(3030, function () {
globals.debug('Server is running on port: 3030', 'success');
});
io.set('authorization', function (handshakeData, accept) {
var domain = handshakeData.headers.referer.replace('http://', '').replace('https://', '').split(/[/?#]/)[0];
if ('www.****.com' == domain) {
globals.debug('New user connected', 'warning');
} else {
globals.debug('Bad site authentication data, chat will be disabled.', 'danger');
return accept('Bad site authentication data, chat will be disabled.', false);
}
});
io.use(function (sock, next) {
var handshakeData = sock.request;
var userToken = handshakeData._query.key;
console.log('The user ' + sock.id + ' has connected');
next(null, true);
});
and when someone comes to website I'm expecting to see in console output "New user connected" and I see it: screen shot and the user should see on the browser console output: "Client side successfully connected with APP." but I doesn't show. Also I tried to emit data to user but it doesn't work too. I can't see any errors or something. This is not the first time I'm working with sockets but the first time facing such as problem. Maybe there is any error reporting methods to handle errors or something? Also I can't see output on io.use(....) method
The solution is to pass "OK" sign just after authenticating to do the next method:
io.set('authorization', function (handshakeData, accept) {
var domain = handshakeData.headers.referer.replace('http://', '').replace('https://', '').split(/[/?#]/)[0];
if ('www.****.com' == domain) {
globals.debug('New user connected', 'warning');
accept(null, true);
} else {
globals.debug('Bad site authentication data, chat will be disabled.', 'danger');
return accept('Bad site authentication data, chat will be disabled.', false);
}
});

Resources