summaryrefslogblamecommitdiffstats
path: root/inc/rpc.inc.php
blob: 83029e41b3345c4eebb23f121a592f5654cd02b5 (plain) (tree)


























































                                                                                                             
<?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;
	}

}