summaryrefslogtreecommitdiffstats
path: root/inc/rpc.inc.php
diff options
context:
space:
mode:
Diffstat (limited to 'inc/rpc.inc.php')
-rw-r--r--inc/rpc.inc.php59
1 files changed, 59 insertions, 0 deletions
diff --git a/inc/rpc.inc.php b/inc/rpc.inc.php
new file mode 100644
index 0000000..83029e4
--- /dev/null
+++ b/inc/rpc.inc.php
@@ -0,0 +1,59 @@
+<?php
+
+/**
+ * Interface to the external rpc.
+ */
+class RPC
+{
+
+ /**
+ * UDP socket used for communication with the rpc
+ * @var resource
+ */
+ private static $sock = false;
+
+ private static function init()
+ {
+ if (self::$sock !== false)
+ return;
+ self::$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
+ socket_set_option(self::$sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 0, 'usec' => 300000));
+ socket_set_option(self::$sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));
+ socket_connect(self::$sock, '127.0.0.1', 1333);
+ }
+
+ public static function submit($data)
+ {
+ self::init();
+ if (empty($data)) {
+ $data = '{}';
+ } else {
+ $data = json_encode($data);
+ }
+ $sent = socket_send(self::$sock, $data, strlen($data), 0);
+ if ($sent != strlen($data)) {
+ return 'RPC send error';
+ }
+ $reply = self::readReply();
+ if ($reply === false) {
+ return 'RPC receive error';
+ }
+ return $reply;
+ }
+
+ /**
+ * Read reply from socket.
+ *
+ * @return mixed read reply as astring, or error message
+ */
+ private static function readReply()
+ {
+ for ($i = 0; $i < 3; ++$i) {
+ $bytes = socket_recvfrom(self::$sock, $buf, 90000, 0, $bla1, $bla2);
+ if ($bytes !== false)
+ return $buf;
+ }
+ return false;
+ }
+
+}