我在 PHP 中有一些连接到套接字的代码。在写信的时候,我的管道断断续续。如果再次写入管道,问题似乎消失了。我想知道需要什么(最安全的方法)才能从中恢复。我还想知道 socket_write 是否可以在不写入传递给它的完整字符串的情况下返回。这是我目前所拥有的。
function getSocket() {
$socket = socket_create( AF_UNIX, SOCK_STREAM, 0 );
if ( $socket === FALSE ) {
throw new Exception(
"socket_create failed: reason: " . socket_strerror( socket_last_error() ));
}
}
$result = socket_connect($socket, $address);
if ($result === false) {
throw new Exception("socket_connect() failed.\nReason: ($result) " .
socket_strerror(socket_last_error($socket)));
}
return $socket;
}
function writeSocket($stmt) {
$tries = 0;
$socket = getSocket();
do {
// Is is possible that socket_write may not write the full $stmt?
// Do I need to keep rewriting until it's finished?
$writeResult = socket_write( $socket, $stmt, strlen( $stmt ) );
if ($writeResult === FALSE) {
// Got a broken pipe, What's the best way to re-establish and
// try to write again, do I need to call socket_shutdown?
socket_close($socket);
$socket = getSocket();
}
$tries++;
} while ( $tries < MAX_SOCKET_TRIES && $writeResult === FALSE);
}