Question

On an apache server using the worker MPM, is it somehow possible to open up multiple persistent sockets to the same TCP address?

When I do the following:

$SocketA = pfsockopen('tcp://domain.com', 80);
$SocketB = pfsockopen('tcp://domain.com', 80);

I get two independent socket resources, yet with the same underlying connection (I can tell because if I write to $SocketA I can read the remote response from $SocketB and vice versa). I would like to have two separate persistent connections.

Is this possible to do?

Was it helpful?

Solution

It would be possible but you would need to use a different hostname/ip address for the second persistent connection.

Reason being, if the host you are connecting to is exactly the same (host and port), it will return the existing persistent connection if it exists, rather than creating a new one.

PHP tracks persistent connections by internally creating a hash value based on the host and port (source):

spprintf(&hashkey, 0, "pfsockopen__%s:%ld", host, port);

Therefore if you use the same host and port for $socketB you are going to get back the existing connection from $socketA. PHP stores this hash value along with the connection, so the next time you call pfsockopen, it regenerates the hash and then looks it up, if it finds it, the old connection is returned.

On socket B, you could try connecting directly to the IP address, or alias some other hostname to the first one so you ultimately get 2 connections to the same location, but you trick PHP into creating 2 connections. These are both workarounds though and are not exactly portable.

For the most part the answer is yes and no, you can't use the same host and port to get 2 connections, but you could work around it using a trick which may be confusing or cause unforseen problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top