3

I have a netcat server, running from command line:

netcat -l -q0 -p 9999 -c "tesseract stdin stdout -l spa"

I can connect to this server using netcat client:

cat /tmp/autogenerado.jpg | netcat 127.0.0.1 9999

So, I send a jpeg file to another server, and receive the OCR'ed data in client.

I want to do this in PHP:

$fp = fsockopen("tcp://127.0.0.1:9999", $errno, $errstr); 

if (!$fp) {
    echo "{$errno}: {$errstr}\n";
    die();
}

fwrite($fp, $jpeg);

$contents = stream_get_contents($fp);

fclose($fp);

return $contents;

But the script hangs on stream_get_contents. I think it is because the netcat server doesn't know when the PHP client has finished sending data.

Is it possible to send an EOF ?

Joe Watkins
  • 17,032
  • 5
  • 41
  • 62
Augusto Beiro
  • 73
  • 1
  • 5
  • What return value are you getting from `fwrite`? Are you getting any errors? This may also help you: http://stackoverflow.com/questions/20684777/php-stream-get-contents-hangs-at-the-end-of-the-stream – Tom Wright Feb 10 '16 at 11:41

2 Answers2

3

You need to shutdown the socket for writing, something like this:

<?php
$stream = stream_socket_client("tcp://whatever:9999", $errno, $errstr);

if (!$stream) {
    echo "{$errno}: {$errstr}\n";
    die();
}

fwrite($stream, $jpeg);

stream_socket_shutdown($stream, STREAM_SHUT_WR); /* This is the important line */

$contents = stream_get_contents($stream);

fclose($stream);

return $contents;
?>
Joe Watkins
  • 17,032
  • 5
  • 41
  • 62
2

For reference, final working code is:

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($sock, "10.187.252.35", 9999);
socket_send($sock,$bdata,strlen($bdata),MSG_EOR):
socket_shutdown ($sock,1);
while ($out = socket_read($sock, 2048)) {
    echo $out;
}
socket_close($sock);
Augusto Beiro
  • 73
  • 1
  • 5