Search code examples
phpreactphp

Reactphp can't get total data on stream


im using reactphp library , and im working with a device that sends packages in different sizes. My problem is when i get the data

 $stream->on('data', function ($data, React\Stream\ReadableStreamInterface $stream) {
            $this->respuesta .= $data;
            $stream->close();
        });

I only get a part of the first package. Is there a way to keep waiting until the device sends all the data?

Here, on the wireshark capture the last package is the one that i cant get with react.

    $loop = React\EventLoop\Factory::create();

    $dnsResolverFactory = new React\Dns\Resolver\Factory();
    $dns = $dnsResolverFactory->createCached('8.8.8.8', $loop);

    $connector = new React\SocketClient\Connector($loop, $dns);

    $connector->create($this->host, $this->port)->then(function (React\Stream\Stream $stream) use ($hex) {
        $stream->write($hex);
        $stream->on('data', function ($data, React\Stream\ReadableStreamInterface $stream) {
            $this->respuesta .= $data;
            $stream->close();
        });
    });

    $loop->run();

Solution

  • It appears you are closing the connection right after receiving the data... You should keep this connection open until after you receive all of the data. The data event is dispatched after receiving some data, not all data.

    Typically this is implementation specific, if your dealing with RPC style api, the client sending the request may not care about acknowledgment from the service and cut the connection after sending the data; in this case you should accumulate your buffer on the data event, and then process it on the end event.

    If you want to keep the connection open, and send discrete chunks of information, typically you either lead the data package with the size of the package, allowing you to know how much of the buffer to fill before processing, or you can send a delimiter (typically a null byte) that marks the end of the package.