4
由於某些原因,當我向端口發送消息並嘗試通過緩衝區讀取消息時,它始終掛起,因爲socket.on('end')
似乎無法到達。有任何想法嗎?節點JS讀取緩衝數據
var net = require('net');
var buffer = [];
var server = net.createServer(function(socket) {
socket.on('data', function(data) {
buffer.push(data);
});
socket.on('end', function() {
try {
var data = buffer.join("");
console.log(data);
socket.end('ok');
} catch (e) {
console.log('Error: ' + e.message);
return;
}
});
});
server.listen(3000, '127.0.0.1');
*編輯:這裏是發送命令的PHP ...
public function sendDaemonCommand($address, $template_id, $params = array()) {
$port = 3000;
$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->logError("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->logError("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
if (socket_write($sock, $command) === false) {
$this->logError("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_close($sock);
return false;
}
// Read back from socket
if (($out = socket_read($sock, 1024)) !== false) {
$out = trim($out);
if ($out == "") {
$this->logError("No message received back from socket 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->logError("Failed to read from socket on " . $address . "\n\n" . socket_strerror(socket_last_error($sock)) . "\n\nCommand:\n\n" . $command. "\n" . $this->functionTraceback());
socket_close($sock);
return false;
}
socket_close($sock);
return $out;
}
我們需要查看連接的客戶端。這是沒有結束連接的客戶。 – Raynos
請參閱編輯謝謝! – fire
@fire也許PHP在關閉之前等待數據回來,而node.js在發送數據之前等待套接字關閉('.end(「ok」)') – Raynos