How to create SSL connection in PHP using SO_KEEPALIVE?

I have a simple PHP code that creates an SSL connection

$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->sslPem);
stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->passPhrase);

$this->apnsConnection = stream_socket_client('ssl://'.$this->apnsHost.':'.$this->apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

But do you know how to set SO_KEEPALIVE to true? I also tried STREAM_CLIENT_PERSISTENT, which is not the same.

+3
source share
3 answers

Have you checked (via network tracing) that you need to set the socket option?

What do you send over a socket? HTTP / HTTPS represents its own function of reusing a connection through the "Connection" header, so the option in the socket does not have to be set by you.

+1
source

SO_KEEPALIVE as in

SO_KEEPALIVE ( "keepalive probe" ) , ( 2 ) - .
?
, STREAM_CLIENT_PERSISTENT, socket_set_option ( , ).
+1

Try this:

$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->sslPem);
stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->passPhrase);

$this->apnsConnection = stream_socket_client('ssl://'.$this->apnsHost.':'.$this->apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);

$is_keepalive = 0;
// https://www.php.net/manual/ru/function.socket-import-stream.php
$socket = socket_import_stream($this->apnsConnection);
if (socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1)) {
    $is_keepalive = socket_get_option($socket, SOL_SOCKET, SO_KEEPALIVE);
    //echo 'SO_KEEPALIVE: ' . $is_keepalive . PHP_EOL;
} else {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if ($is_keepalive) {
    // https://www.php.net/manual/ru/function.socket-export-stream.php
    $this->apnsConnection = socket_export_stream($socket);
}

// TEST
//$socket = socket_import_stream($this->apnsConnection);
//echo 'SO_KEEPALIVE: ' . socket_get_option($socket, SOL_SOCKET, SO_KEEPALIVE);
0
source

Source: https://habr.com/ru/post/1712419/


All Articles