开发者

Node JS read in buffered data

For some reason when I send a message to the port and attempt to read it in via a buffer, it always hangs as socket.on('end') never seems to be reached. Any ideas?

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');

*Edit: here is the PHP that sends the command...

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;
}


Set allowHalfOpen to true in net.createServer then use socket_shutdown($sock, 1) after write and socket_shutdown($sock, 0) after read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜