여기에 readme 예제를 사용하고 있습니다.
https://github.com/amphp/websocket-client/blob/master/README.md
use Amp\Websocket;
use Amp\Delayed;
use Amp\Websocket\Connection;
use Amp\Websocket\Handshake;
use Amp\Websocket\Message;
use function Amp\Websocket\connect;
\Amp\Loop::run(function () use ($fn)
{
try
{
$connection = yield connect('wss://....');
yield $connection->send('{
"action":"authenticate",
"data":{
...
}
}');
while ($message = yield $connection->receive())
{
$payload = yield $message->buffer();
// print the payload
$this->info($payload);
// custom function to parse the payload
$r = $fn($payload);
if ($r == false) {
$this->warn('Connection closed.');
$connection->close();
break;
}
}
}
catch (\Throwable $e) {
$this->isError($e->getMessage(),true);
}
catch (\Exception $e) {
$this->isError($e->getMessage(),true);
}
});
문제 : while 루프는 메시지가 스트림을 통해 전송 될 때만 실행되며 메시지가 없으며 유휴 모드 대기 상태이므로 아무 일도 일어나지 않습니다.
솔루션 : 핑을 수신하거나 핑에서 while 루프를 실행하면서 메시지를 수집하려면 어떻게해야합니까?
예를 들어, 일부 정보 (예 : 소켓이 열려 있어야 함)를 확인하는 것을 제어하고 싶지만 메시지가 스트림을 통해 올 때만 확인할 수 있습니다. 활동이 있으므로 정보가 전송되지 않으면 영원히 기다립니다.
핑은 RFC에 기반한 웹 소켓의 표준입니다 : https://tools.ietf.org/html/rfc6455
에 Rfc6455Connection
연결 클래스, 핑이있다, 그러나이 접근하거나 직접를 사용하는 방법에 대한 문서가 제공되지 않습니다.
핑에서 while 루프를 실행하고 동시에 메시지가 있는지 확인하는 것이 좋습니다. 이것이 가능합니까?
amphp/websocket-client
핑을 자동으로 처리하고 이에 응답하므로 API 사용자가 가져야 할 유일한 문제는 메시지 수신입니다.
Amp를 사용하면 Amp\call
/를 사용하여 언제든지 여러 코 루틴을 생성 Amp\asyncCall
할 수 있으므로 예를 들어 유휴 시간 후에 연결을 닫을 수 있습니다.
Loop::run(function () {
try {
$connection = yield connect($uri);
asyncCall(function () use ($connection) {
while (true) {
if (!$this->isActive()) {
$connection->close();
break;
}
yield Amp\delay(1000);
}
});
yield $connection->send('...');
while ($message = yield $connection->receive()) {
$payload = yield $message->buffer();
$r = $fn($payload);
if ($r == false) {
$this->warn('Connection closed.');
$connection->close();
break;
}
}
} catch (\Exception $e) {
$this->isError($e->getMessage(),false);
}
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다