Example #1
0
 /**
  * @param string $payload
  *
  * @return string
  * @throws ConnectionException
  */
 public function send($payload)
 {
     if (!$this->ws->isConnected()) {
         throw new ConnectionException(sprintf('Could not connect to "%s"', $this->address));
     }
     $this->ws->send($payload);
     $response = $this->ws->receive();
     if (($opCode = $this->ws->getLastOpcode()) !== 'text') {
         throw new ConnectionException(sprintf('Received non-text frame of type "%s" with text: "%s"', $opCode, $response));
     }
     return $response;
 }
Example #2
0
 public function sendApiRequest($number, $content, $id)
 {
     $client = new Client(getSocketUrl());
     $client->setTimeout(10000);
     $client->send($this->buildApiRegisterRequest());
     $result = $client->receive();
     hist('api.response', $result, $id);
     $client->send($this->buildApiRequest($number, $content));
     $result = $client->receive();
     hist('api.response', $result, $id);
     hist('sms.send', 'Sent SMS to ' . $number . ': ' . $content, $id);
 }
 public function testRandomInt()
 {
     /**
      * Message returned by WebSocket server is string
      */
     $txt = (string) rand(10, 1000);
     $ws = new Client("ws://{$GLOBALS["ip"]}:{$GLOBALS["port"]}/?service=hello");
     $ws->send($txt);
     $this->assertEquals($txt, $ws->receive());
     $ws->close();
 }
Example #4
0
 /**
  * @param                    $method
  * @param                    $uri
  * @param array              $options
  * @param null|bool|\Closure $successCallback
  * @param null|bool|\Closure $failCallback
  *
  * @return bool|null|\StdClass
  * @throws Exception
  */
 public function request($method, $uri, $options = [], $successCallback = null, $failCallback = null)
 {
     if (!$successCallback && !$failCallback) {
         $json = null;
         // If there's no callbacks defined we assume this is a RESTful request
         Logger::getInstance()->debug($method . ' ' . $uri . ' ' . json_encode($options));
         $options = array_merge($this->defaultOptions, $options);
         $guzzle = new GuzzleHttp\Client(['base_uri' => self::BASE_URL_REST]);
         $res = $guzzle->request($method, $uri, $options);
         if ($res->getHeader('content-type')[0] == 'application/json') {
             $contents = $res->getBody()->getContents();
             Logger::getInstance()->debug($contents);
             $json = json_decode($contents);
         } else {
             throw new Exception("Server did not send JSON. Response was \"{$res->getBody()->getContents()}\"");
         }
         return $json;
     } else {
         // Use the STREAM API end point
         $Uri = new Uri(self::BASE_URL_STREAM);
         $Uri->setUserInfo($this->defaultOptions['auth'][0] . ':' . $this->defaultOptions['auth'][1]);
         $Uri->setPath($uri);
         if (isset($options['query'])) {
             $Uri->setQuery($options['query']);
         }
         $WSClient = new WebSocket\Client($Uri);
         Logger::getInstance()->debug($Uri);
         if (!$successCallback instanceof \Closure) {
             $successCallback = function ($response) {
                 $info = json_decode($response);
                 if (property_exists($info, 'output')) {
                     Logger::getInstance()->info(json_decode($response)->output);
                 } elseif ($info->type == 'error') {
                     // output error info
                     Logger::getInstance()->info($info->message);
                 }
             };
         }
         if (!$failCallback instanceof \Closure) {
             $failCallback = function (\Exception $exception) {
                 Logger::getInstance()->info($exception->getMessage());
             };
         }
         try {
             while ($response = $WSClient->receive()) {
                 $successCallback($response);
             }
         } catch (\Exception $e) {
             $failCallback($e);
         }
         return true;
     }
 }
 function onmessage()
 {
     $evt = parent::receive();
     $data = json_decode($evt->data);
     if ($data->cmd == 'awk') {
         $this . fetch($data->qname);
     }
     if ($data->cmd == 'nomsg') {
         $this->isleep($data->qname);
     }
     if ($data->cmd == 'msg') {
         $this->qbacks[$data->qname]($data->msg);
         $this->fetch($data->qname);
     }
 }
 function work()
 {
     $evt = parent::receive();
     $data = json_decode($evt);
     if (!isset($data->cmd)) {
         return false;
     }
     if ($data->cmd == 'awk') {
         $this->fetch($data->qname);
     }
     if ($data->cmd == 'nomsg') {
         $this->isleep($data->qname);
     }
     if ($data->cmd == 'msg') {
         $func = $this->qbacks[$data->qname];
         call_user_func($func, $data);
         $this->fetch($data->qname);
     }
     return true;
 }
 /**
  * Main execution loop
  * @throws \Exception
  */
 protected function processLoop()
 {
     while (true) {
         try {
             $data = $this->client->receive();
             $parsedData = json_decode($data, true);
             if ('message' === Ar::get($parsedData, 'type') && 'bot_message' !== Ar::get($parsedData, 'subtype')) {
                 echo sprintf("[INFO] Got message: '%s' from %s in %s\n", Ar::get($parsedData, 'text') ?: '<nothing>', Ar::get($parsedData, 'user') ?: 'bot', Ar::get($parsedData, 'channel') ?: 'unknown channel');
                 try {
                     $this->curlRequest->getCurlResult($this->serverUrl, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => ['message' => $data]]);
                 } catch (\Exception $e) {
                 }
             }
         } catch (Exception $e) {
             $result = $this->curlRequest->getCurlResult($this->authUrl);
             $result = json_decode($result['body'], true);
             $this->socketUrl = $result['url'];
             $this->client = $this->createClient();
         }
     }
 }
 /**
  * Reset the receive counter
  */
 public function receive()
 {
     $this->fragment_count['receive'] = 0;
     return parent::receive();
 }
Example #9
0
 /**
  * @dataProvider serverPortProvider
  */
 public function testAddingHeaders($port)
 {
     $ws = new Client('ws://localhost:' . self::$ports[$port] . '/' . $this->test_id, array('headers' => array('X-Cooler-Than-Beeblebrox' => 'Slartibartfast')));
     $ws->send('Dump headers');
     $this->assertRegExp("/GET \\/{$this->test_id} HTTP\\/1.1\r\n" . "host: localhost:" . self::$ports[$port] . "\r\n" . "user-agent: websocket-client-php\r\n" . "connection: Upgrade\r\n" . "upgrade: websocket\r\n" . "sec-websocket-key: .*\r\n" . "sec-websocket-version: 13\r\n" . "x-cooler-than-beeblebrox: Slartibartfast\r\n/", $ws->receive());
 }
Example #10
0
 public static function streaming($prms, $callback)
 {
     $file_path = dirname(__FILE__) . '/vendor/autoload.php';
     if (file_exists($file_path) && is_readable($file_path)) {
         require_once $file_path;
     } else {
         throw new Exception('You can not use Streaming API.You should check including libray.');
     }
     switch ($prms['currency_pair']) {
         case 'btc_jpy':
         case 'mona_jpy':
         case 'mona_btc':
             break;
         default:
             throw new Exception('Argument has not been set.');
             return 0;
             break;
     }
     $ws = self::STREAMING_BASE_URL . '?' . http_build_query($prms);
     $client = new Client($ws);
     while (true) {
         try {
             $json = $client->receive();
             $data = json_decode($json);
             $callback($data);
         } catch (WebSocket\ConnectionException $e) {
             $clinet = new Client($ws);
         }
     }
 }
Example #11
0
<?php

require dirname(dirname(__FILE__)) . '/vendor/autoload.php';
use WebSocket\Client;
$client = new Client("ws://localhost:{$argv[1]}");
$client->send($argv[2]);
echo $client->receive();
 /**
  * Receive
  *
  * @return string
  */
 public function receive()
 {
     return $this->websocket->receive();
 }