reactphp / socket

Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP.

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Get write response

leocharrua opened this issue · comments

Hello, I know all here is non-blocking and is ok. But, how I can get the result after I do a write tcp package?
For example, I has a tcp connection with the server, but in some point, the server get down. The client do the write, but didn't get any advice that the connection is down.
I'm checking the connection on('error') event, but I didn't get anything there.

Thanks for your help.

@leocharrua Thanks for bringing this up, this is an interesting question!

This packages is entirely asynchronous and event-driven, so one first has to get used to a different kind of control flow.

The write() method is asynchronous. This mean when you call it, it will not actually write anything just yet. Instead, it will buffer the data until the event loop signals that a write can be performed at a later time (usually that happens a few microseconds later). If the connection is already known to be down, this or course won't try to send and instead return a false value. Other than that, this also implies that this method cannot know whether a call is "successful" when the connection is still alive.

If the server properly closes a connection, it would send a TCP/IP FIN flag. The client would detect this and emit a close event that you can listen for.

$connection->on('close', function () {
    echo 'Connection closed' . PHP_EOL;
});

A successful close event does not usually constitute an error. The connection may emit an error event if the connection is interrupted in an unexpected way. The client would detect this and emit an error event that you can listen for:

$connection->on('error', function (Exception $e) {
    echo 'Error: ' . $e->getMessage() . PHP_EOL;
});

Keep in mind that connections can also be interrupted (think hard power down), so the server may have no chance to send a FIN to the client. In this case, you would probably want to apply some kind of higher level protocol to send keepalive messages (heartbeats). If you don't receive a reply in x seconds, you can manually close() the connection.

I hope this helps 👍

Excelent @clue . Very clear answer. Thanks for all your work.