出现某些原因时,当我通过端口发送消息并尝试通过缓冲区读取时,它总是挂起,因为
socket.on('end')
似乎永远不会被触发。有什么想法吗?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;
}
.end("ok")
)。 - Raynossocket.on('end')
代码,但是我该如何解决这个问题? - firesocket_close($sock)
会触发on('end')
。 - Raynossocket_read($sock, 1024)
不会阻塞直到读取到数据吗?试着在读取之前调用socket_close
。 - Raynos