|
| 1 | +<?php |
| 2 | +/* |
| 3 | +
|
| 4 | +Bridge Client PHP Class |
| 5 | +------------------------ |
| 6 | +by Luca Soltoggio - 2013 |
| 7 | +
|
| 8 | +Released under GPL v.2 license |
| 9 | +
|
| 10 | +Requirements |
| 11 | +------------ |
| 12 | +In order to use this class you have to install php5, php5-mod-sockets and php5-mod-json and php5-cgi or php5-cli |
| 13 | +
|
| 14 | +Usage |
| 15 | +----- |
| 16 | +The usage is the same as bridgeclient.py |
| 17 | +You have only two methods: get and put (see example.php) |
| 18 | +
|
| 19 | +*/ |
| 20 | + |
| 21 | +error_reporting(E_ERROR); |
| 22 | + |
| 23 | +class bridgeclient { |
| 24 | + |
| 25 | + private $service_port = 5700; |
| 26 | + private $address = "127.0.0.1"; |
| 27 | + private $socket; |
| 28 | + |
| 29 | + private function connect() { |
| 30 | + ($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) |
| 31 | + || die("socket_create() failed: " . socket_strerror(socket_last_error()) . "\n"); |
| 32 | + socket_set_option($this->socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>3, "usec"=>0)); |
| 33 | + socket_connect($this->socket, $this->address, $this->service_port) |
| 34 | + || die("socket_connect() failed: " . socket_strerror(socket_last_error($this->socket)) . "\n"); |
| 35 | + } |
| 36 | + |
| 37 | + private function disconnect() { |
| 38 | + socket_close($this->socket); |
| 39 | + } |
| 40 | + |
| 41 | + private function sendcommand($command,$key,$value="") { |
| 42 | + $jsonreceive = ""; |
| 43 | + $obraces=0; |
| 44 | + $cbraces=0; |
| 45 | + |
| 46 | + $this->connect(); |
| 47 | + |
| 48 | + $jsonsend = '{"command":"'.$command.'","key":"'.$key.'","value":"'.$value.'"}'; |
| 49 | + socket_write($this->socket, $jsonsend, strlen($jsonsend)); |
| 50 | + |
| 51 | + do { |
| 52 | + socket_recv($this->socket, $buffer, 1,0); |
| 53 | + $jsonreceive.=$buffer; |
| 54 | + if($buffer == "{") $obraces++; |
| 55 | + if($buffer == "}") $cbraces++; |
| 56 | + } while ($obraces != $cbraces); |
| 57 | + |
| 58 | + $this->disconnect(); |
| 59 | + |
| 60 | + $jsonarray=json_decode($jsonreceive); |
| 61 | + if ($jsonarray->{'value'} == NULL) $jsonarray->{'value'}="None"; |
| 62 | + |
| 63 | + return $jsonarray->{'value'}; |
| 64 | + } |
| 65 | + |
| 66 | + public function get($key) { |
| 67 | + return $this->sendcommand("get",$key); |
| 68 | + } |
| 69 | + |
| 70 | + public function put($key,$value) { |
| 71 | + return $this->sendcommand("put",$key,$value); |
| 72 | + } |
| 73 | + |
| 74 | +} |
| 75 | +?> |
0 commit comments