/** * @param bool $insert * @param array $changedAttributes * @throws \WebSocket\BadOpcodeException */ public function afterSave($insert, $changedAttributes) { Yii::trace('try to send a call information to site ' . $this->paramint, 'app\\modules\\event\\PhoneEvent::afterSave'); //initialize the response object $res = []; $res['type'] = 'call'; $res['site'] = $this->paramint; $WSServer = \Yii::$app->params['websocketServerProtocol'] . \Yii::$app->params['clientCallWebsocketServerHost'] . ':' . \Yii::$app->params['clientCallWebsocketServerPort']; $client = new Client($WSServer); $timeinfo = Yii::$app->formatter->asDateTime($this->updated_at); $html = <<<EOF \t<div style="width:250px" class="event_notification"> \t\t<div class="{$this->action}"> \t\t\t<i class="fa fa-phone"></i> {$this->action} \t\t</div> \t\t<small>{$timeinfo}</small><br> \t\t<a href="#"> \t\t\tYou have an {$this->mod_table} call from {$this->paramtext}. \t\t</a> \t</div> EOF; $res['data'] = $html; try { $client->send(Json::encode($res)); } catch (ConnectionException $e) { echo "\n" . microtime(true) . " Client died: {$e}\n"; } return parent::afterSave($insert, $changedAttributes); }
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(); }
/** * @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; } }
/** * @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; }
/** * @return string * * @throws \WebSocket\ConnectionException */ protected function receive_fragment() { $returnValue = parent::receive_fragment(); if ($this->getLastOpcode() === 'ping') { $this->send('pong', 'pong', true); } return $returnValue; }
function subsendcmd($qname) { $obj = new \stdClass(); $obj->qname = $qname; $obj->cmd = "SUB"; $data = json_encode($obj); parent::send($data); }
/** * Send message to WebSocket server * If server offline - attempt to reconnect * @param $message * @throws \WebSocket\BadOpcodeException */ private function sendWSMessage($message) { if (is_array($message) || is_object($message)) { $message = json_encode($message); } try { $this->wsClient->send($message); } catch (\Exception $e) { $this->logger->error(__METHOD__ . ' | ' . 'WebSocket client error. Reason: ' . $e->getMessage() . '.'); } }
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); }
/** * 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(); } } }
<?php require dirname(__DIR__) . '/vendor/autoload.php'; use WebSocket\Client; $client = new Client("ws://85.214.151.129:8080"); $client->send("[{CHECK\\/\\/TIMEOUT}]");
/** * Increment the fragment recieve counter */ protected function receive_fragment() { $this->fragment_count['receive']++; return parent::receive_fragment(); }
/** * @dataProvider serverPortProvider * * @expectedException \InvalidArgumentException * @expectedExceptionMessage Stream context in $options['context'] isn't a valid context */ public function testSetInvalidStreamContextOptions($port) { $context = false; $options = array('context' => $context); $ws = new Client('ws://localhost:' . self::$ports[$port], $options); $ws->send('foo'); }
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); } } }
<?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();
public function testSetFragmentSize() { $ws = new Client('ws://localhost:' . self::$port); $size = $ws->setFragmentSize(123)->getFragmentSize(); $this->assertSame(123, $size); }
<?php require dirname(__DIR__) . '/vendor/autoload.php'; use WebSocket\Client; $client = new Client("ws://85.214.151.129:8080"); $client->send("[{INSERT\\/\\/CLICK\\/\\/COORDINATES}]"); $client->close(); sleep(60); $client = new Client("ws://85.214.151.129:8080"); $client->send("[{INSERT\\/\\/MOUSEMOVE\\/\\/COORDINATES}]"); $client->close(); sleep(60); $client = new Client("ws://85.214.151.129:8080"); $client->send("[{INSERT\\/\\/SCROLL\\/\\/COORDINATES}]"); $client->close(); ?>
/** * @expectedException WebSocket\BadOpcodeException * @expectedExceptionMessage Bad opcode 'bad_opcode' */ public function testSendBadOpcode() { $ws = new Client('ws://localhost:' . self::$port); $ws->send('foo', 'bad_opcode'); }
/** * Receive * * @return string */ public function receive() { return $this->websocket->receive(); }
<?php require '../../websocket-php/lib/Base.php'; require '../../websocket-php/lib/Client.php'; use WebSocket\Client; echo "trying to do something useful<br />"; /* $client = new Client("ws://echo.websocket.org/"); $client->send("Hello WebSocket.org! Buh!"); */ $client = new Client("ws://bot.betatechnologies.info:8000/"); if ($_REQUEST['msg']) { $client->send($_REQUEST['msg']); } else { $client->send("Hello My server"); } echo $client->receive(); // Will output 'Hello WebSocket.org!'