Skip to content
Advertisement

PHP socket_read waits for data to read

I’m new to socket stuff, here is my piece of code:

while (true) {
    $status = $this->client->read();
    echo $status;

    $this->eventQueue->hasEventToSend() ? $this->client->send($this->eventQueue->getEvent()) : null;
}

client read method is just:

try {
    $status = socket_read($this->socket, $length);
} catch (Throwable $exception) {
    $this->reConnect();
    Log::error($exception->getMessage());

    $status = false;
}

return (string) $status;

Nothing will be executed after $status = $this->client->read(), untill socket_read() reads new data. I would like to stop socket_read() acting like waiting for data to read or call socket_read() only when there is any data to read. I couldn’t get any idea, how to achive that, so I’m asking here 😉

Advertisement

Answer

By default reading operations are always blocking. You can either use

socket_set_nonblock($socket)

before calling read() to prevent socket from blocking in read operations, or you can use

socket_select()

to check if data is available before reading it.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement