Skip to content

Instantly share code, notes, and snippets.

@totoCZ
Last active August 8, 2017 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totoCZ/4430857313539b2585a5175ca3c1ed81 to your computer and use it in GitHub Desktop.
Save totoCZ/4430857313539b2585a5175ca3c1ed81 to your computer and use it in GitHub Desktop.
final php socket client for golang json rpc server
<?php
$timeout = 1;
$chunkSize = 4;
function callRPC($host, $targets, $timeout, $chunkSize) {
$sockets = [];
$errno = 0;
$errstr = '';
// Send.
$s = stream_socket_client($host, $errno, $errstr, $timeout);
if (!$s) {
echo "$errstr ($errno)\n";
return false;
}
stream_set_blocking($s, 0);
$sockets[] = $s;
$rpc = '';
$successCount = sizeof($targets);
fwrite($s, implode("\n", array_filter($targets)));
// Receive.
$result = '';
while (count($sockets)) {
$read = $sockets;
stream_select($read, $w = null, $e = null, $timeout);
if (count($read)) {
foreach ($read as $r) {
$id = array_search($r, $sockets);
$data = fread($r, $chunkSize);
$result .= $data;
if (false !== strpos($data, "\n")) {
$successCount -= substr_count($data, "\n");
if (0 == $successCount) {
$result = trim($result);
fclose($r);
unset($sockets[$id]);
}
}
}
} else {
throw new Exception("timeout");
break;
}
}
return explode("\n", $result);
}
$result = callRPC(
"unix:///var/run/pingator.sock",
[
/*'{"method":"Arith.Multiply","params":[{"A":1,"B":9}],"id":0}',
'{"method":"Arith.Divide","params":[{"A":10,"B":90}],"id":1}',
'{"method":"Compose.Details","params":[{"Foo":"10","Bar":"90"}],"id":2}',*/
'{"method":"Ping.V2Rocket","params":[{"IP":"www.yahoo.com"}],"id":3}',
'{"method":"Ping.V2Rocket","params":[{"IP":"72.52.91.14"}],"id":4}',
],
$timeout,
$chunkSize
);
print_r($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment