3

没有足够的声誉来正确标记它(ruby、PHP、socket、rescue)

我已经很久没有练习我的 PHP 了,因为我一直在做更多的 Ruby 脚本。我有点不好意思在这方面寻求帮助。

我知道,在 Ruby 中,我可以使用救援来防止脚本在出错的情况下崩溃,我希望用 PHP 实现同样的目标。

例如,在 Ruby 中:

require 'socket'

begin puts "Connecting to host..." 
host = TCPSocket.new("169.121.77.3", 333) 
# This will (intentionally) fail to connect, triggering the rescue clause. 
rescue puts "Something went wrong." 
# Script continues to run, allowing, for example, the user to correct the host IP. 
end

我的 PHP 代码有点乱——已经很久了。

function check_alive($address,$service_port) { 
    /* Create a TCP/IP socket. */ 
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 
    if ($socket === false) { 
      echo socket_strerror(socket_last_error());
    } 
    else { 
      echo null; 
    } 
    $result = socket_connect($socket, $address, $service_port); 
    if ($result === false) { 
       echo socket_strerror(socket_last_error($socket)); 
       return 1; 
    }
    else { 
       echo null; 
    } 
    socket_close($socket); 
    return 0; } 
    $hosts = [...]; 
    // list of hosts to check 
    foreach($hosts as $key=>$host) { 
       check_alive($hosts); 
    }

本质上,我有一系列主机,我想检查它们是否还活着。不需要所有主机都活着,所以这就是我卡住的地方 - 数组中的第一个死主机会使脚本崩溃。

任何建议将不胜感激 - 我愿意接受我不完全理解 PHP 中的套接字连接。

4

2 回答 2

5

PHP 等价物是:

try { ... } catch (...) { ... }

如果您使用的是 PHP 5.5,还有:

try { ... } catch (...) { ... } finally { ... }

您可以有多个 catch 子句,每个子句捕获一个不同的异常类。

finally 部分始终运行,包括引发异常时。

于 2013-11-19T22:59:11.347 回答
2

以下是异常处理的 PHP 等效项:

try { // equivalent of Ruby `begin`

} catch(Exception $e) { // equivalent of Ruby `rescue(e)`

}
于 2013-11-19T23:00:26.573 回答