我编写一个命令,然后通过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