Client.class.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. class Client {
  3. public $socket;
  4. public function connect(){
  5. $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  6. $response = '';
  7. if ($this->socket !== false) {
  8. if (!socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1))
  9. throw new Exception(utf8_encode(socket_strerror(socket_last_error($this->socket))));
  10. $result = @socket_connect( $this->socket, '127.0.0.1', 9999);
  11. if(!$result){
  12. $this->socket = null;
  13. throw new Exception('Erreur connexion au serveur socket depuis yana-server, le serveur est il allumé ? '.utf8_encode(socket_strerror(socket_last_error())));
  14. }
  15. }
  16. }
  17. public function disconnect(){
  18. if($this->socket==null) return;
  19. socket_shutdown($this->socket);
  20. socket_close($this->socket);
  21. $this->socket = null;
  22. }
  23. public function send($msg,$receive = false){
  24. if($this->socket==null) return;
  25. $in = json_encode($msg);
  26. $in .= '<EOF>';
  27. socket_write($this->socket, $in, strlen($in));
  28. if(!$receive) return $in;
  29. $in = '';
  30. $start = time();
  31. $go = false;
  32. socket_set_option($this->socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>1, "usec"=>0));
  33. while (!$go) {
  34. $in .= @socket_read($this->socket, 2048);
  35. if((time()-$start) > 1) $go = true;
  36. }
  37. return $in;
  38. }
  39. public function talk($parameter){
  40. //echo 'Execution envois de parole vers un client : '.$parameter;
  41. return $this->send(array("action"=>"TALK","parameter"=>$parameter));
  42. }
  43. public function sound($parameter){
  44. return $this->send(array("action"=>"SOUND","parameter"=>$parameter));
  45. }
  46. public function execute($parameter){
  47. return $this->send(array("action"=>"EXECUTE","parameter"=>$parameter));
  48. }
  49. public function emotion($emotion){
  50. return $this->send(array("action"=>"EMOTION","parameter"=>$emotion));
  51. }
  52. public function image($image){
  53. return $this->send(array("action"=>"IMAGE","parameter"=>$image));
  54. }
  55. // public static function connect() {
  56. // if(is_null(self::$instance)) {
  57. // self::$instance = new Client();
  58. // }
  59. // return self::$instance;
  60. // }
  61. }
  62. ?>