Home > Enterprise >  How to show all output from fread socket unix in PHP?
How to show all output from fread socket unix in PHP?

Time:09-03

I try show output from socket but the return is showed cut.

<?php


$socket = '/var/run/qemu-server/121.serial1';

$sock = stream_socket_client('unix://'.$socket, $errno, $errstr);

fwrite($sock, $argv[1] . "\r\n");

$data = '';

while ($buffer =  fread($sock, 8128)) $data .= $buffer;

echo $data; 

fclose($sock);

?>

I need this output:

{"VMid":"121","Command":"ls /","Output":"bin\nboot\ndev\netc\nhome\nlib\nlib32\nlib64\nlibx32\nlost found\nmedia\nmnt\nopt\nproc\nroot\nrun\nsbin\nsnap\nsrv\nswap.img\nsys\ntmp\nusr\nvar\n"}

But it only returns:

{"VMid":"121","Command":"ls /","Output"

I tried "stream_set_read_buffer", "file_get_contents" and no success.

CodePudding user response:

I presume here that the server has not had time to fully respond by the time you are polling. You can quickly test this theory by putting a sleep() after you send the instruction (fwrite) before you poll (fread). That's a test solution, not final (as you never know how long to "sleep" for).

What you need for sockets generally are a continuous poll (while loop that basically never ends, but under control so you can pause / exit etc), and continuous buffer read/write (append new content to a buffer; when you either reach the end of expected message OR you read the number of bytes you expect* remove that content from the front of the buffer and leave the remainder for next loop. You can, of course, bomb out at this point if you have everything you need and close the socket or return to polling later.

A common trick is to set the first two/four bytes of the message to the length of the payload, then the payload. So you constantly would poll for those two/four bytes and then read the content based of that. Probably not possible with another system like QEMU, so you'll need to look instead for...? EOL/NL etc?

  • Related