我編寫一個命令,然後通過PHP中的套接字從服務器回讀。我們有20臺服務器都運行一個Node JS腳本,它可以接收這些命令並執行它們。 Node JS腳本將返回PHP回讀的「ok」以確認命令已經通過。然後通過在PHP問題中通過套接字回讀
節點JS腳本偵聽端口9000並設置爲allow half open。
大多數這工作得很好,但是當命令的大批量發送,我們得到的錯誤回到偶爾會認爲,這一時間:
Contents: Message received back from socket was 'Unexpected token {'
Transport endpoint is not connected
傳輸的端點消息建議,我認爲它沒有連接成功。
我不是插座專家,所以我不知道我使用的實現是否「正確」。它大多數時間都有效,但我知道有些功能可能會更好,但我不確定它們的功能,如socket_bind
和socket_listen
。
這是我們正在使用的PHP代碼。任何建議將不勝感激。
public function sendDaemonCommand($address, $template_id, $params = array()) {
$hostname = $this->getHostnameFromPrivateIP($address);
$port = 9000;
$command = array('template_id' => $template_id, 'params' => $params);
$command = json_encode($command);
// Create a TCP Stream socket
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to create socket on " . $address . "\n\n" . socket_strerror(socket_last_error()) . "\n\nCommand:\n\n" . $command . "\n" . $this->functionTraceback());
return false;
}
// Connect to socket
if (socket_connect($sock, $address, $port) === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to connect to socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_close($sock);
return false;
}
// Write command to socket
$_command = $command;
$length = strlen($_command);
while (true) {
$sent = socket_write($sock, $_command, $length);
if ($sent === false) {
$this->mailError("Command Failed - " . $hostname, "Failed to write command to socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_shutdown($sock, 2);
socket_close($sock);
return false;
}
if ($sent < $length) {
$_command = substr($_command, $sent);
$length -= $sent;
}
else {
break;
}
}
socket_shutdown($sock, 1);
// Read back from socket
if (($out = socket_read($sock, 1024)) !== false) {
@socket_shutdown($sock, 0);
$out = trim($out);
if ($out !== "ok") {
$this->mailError("Command Failed - " . $hostname, "Message received back from socket was '" . $out . "' on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_close($sock);
return false;
}
}
else {
$this->mailError("Command Failed - " . $hostname, "Failed to read from socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_shutdown($sock, 0);
socket_close($sock);
return false;
}
socket_close($sock);
return $out;
}
那麼你不應該使用PHP套接字連接到Node.js,這是處理大量打開的連接時真的效率低下。 – alessioalex 2012-01-05 15:01:11
你看過PHP服務器端的netstat ...也許你的本地端口用完了? – 2012-01-05 15:08:05
@alessioalex我還可以在PHP上使用什麼? – fire 2012-01-05 15:17:22