amphp / socket

Non-blocking socket and TLS functionality for PHP based on Amp.

Home Page:https://amphp.org/socket

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Timeout exceeded on multiple request

marioshtika opened this issue · comments

I am sending multiple requests to a TCP client, using the below code

$promises = [];
foreach ($packets as $packet) {
    $promises[] = call(function () use ($packet, $uri) {

        /** @var \Amp\Socket\ClientSocket $socket */
        $socket = yield connect($uri);
        try {
            yield $socket->write($packet);

            $chunk = yield $socket->read(); // modbus packet is so small that one read is enough
            if ($chunk === null) {
                return null;
            }
            return ResponseFactory::parseResponse($chunk);
        } finally {
            $socket->close();
        }
    });
}

try {
    // will run multiple request in parallel using non-blocking php stream io
    $responses = wait(all($promises));
    // print_r($responses);
} catch (Throwable $e) {
    print_r($e);
}

This works fine, but if I have more than 100 packages, I am getting the below error message

Exception 'Amp\Socket\ConnectException' with message 'Connecting to tcp://192.168.0.220:502 failed: timeout exceeded (10000 ms)'

in /vagrant/vendor/amphp/socket/src/DnsConnector.php:82

Is there a limit on how many requests can I send using socket?
Or is this a memory limitation?
Or a network limitation?

The other side probably doesn't accept the connections quickly enough, at least that'd be my first guess. Do you need a new connection for each packet?

If your remote closes the connection after the packet is sent completely, you can use yield Amp\ByteStream\buffer($socket) instead of yield $socket->read(), which will work even if the remote response is fragmented into multiple chunks.

Hello @kelunik and thank you so much. Your guess was correct.
Maybe the other side couldn't accept so many connections.
Also I didn't need a new connection for each packet.
That helped me a lot.
Thank you again.