PHP ソケットを使用して個人プロジェクト用のライブラリを作成しようとしています。そのために、phpUnit を使い始め、(多かれ少なかれ) 定性的なライブラリを学び、書きました。
testConnection メソッドで try/catch ブロックを指定しないと、php は接続がタイムアウトしたというエラーを返します (デバイスが接続されていないため、これは正常です)。ただし、php は、testConnection メソッドではなく、以下の execute メソッドで例外を処理する必要があります。そして、私はこれを理解できないようです。
これはエラーです:
PHPUnit_Framework_Error_Warning : stream_socket_client(): unable to connect to tcp://x.x.x.x:* (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
そこにあってはならないメソッドと try/catch を含むテストクラス:
public function testConnection() {
$adu = new Adu();
$adu->setPort('AS0');
$adu->setData('?');
$command = new Command('x.x.x.x', *);
$command->setAduSent($adu);
try
{
$command->execute();
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
これ (execute メソッド) で例外を処理する必要があります。
public function execute()
{
try {
$this->stream = $this->createStream($this->address, $this->port, $this->timeout);
}
catch(Exception $e) {
$this->logger->error('Exception (' . $e->getCode() . '): ' . $e->getMessage() . ' on line ' . $e->getLine(), $e);
}
$this->send($this->stream, $this->aduSent);
$this->aduReceived = $this->receive($this->stream);
}
private function createStream($address, $port, $timeout = 2)
{
$stream = stream_socket_client('tcp://' . $address . ':' . $port, $errorCode, $errorMessage, $timeout);
if(!$stream) {
throw new Exception('Failed to connect(' . $errorCode . '): ' . $errorMessage);
}
return $stream;
}
解決
try/catch はエラー/警告をキャッチしないため、stream_socket_client によってトリガーされる警告を抑制しなければなりませんでした。次に、戻り値が false またはストリーム オブジェクトであるかどうかを確認します。false の場合、適切な例外をスローします。
$stream = @stream_socket_client('tcp://' . $address . ':' . $port, $errorCode, $errorMessage, $timeout);