Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Can someone explain the pfsockopen function for me? (persistent socket)

Tags:

php

sockets

From PHP.net:

http://www.php.net/manual/en/function.pfsockopen.php

I understand the gist of what this function accomplishes, but I'm still unclear as to whether this will accomplish what I'd like it to. Here is my scenario:

I have a large PHP application that is used by many users simultaneously. Within the application, I'm opening a TCP socket to a remote server for logging messages, etc... It was my hope that I might be able to leverage pfsockopen in order that many fewer connections would need to be opened. For example, user1 signs in - socket opens. User2 signs in, no socket is opened because he can "piggyback" on the socket opened by user1.

Is this possible?

like image 739
tambler Avatar asked Nov 11 '11 19:11

tambler


1 Answers

pfsockopen will indeed keep the socket open when the script ends, allowing it to be re-used from a request to another, effectively opening less connections like you would expect. However, this is not compatible with all SAPIs.

The persistence occurs on a per-process basis. As such, pfsockopen ran in a CLI SAPI will close and re-open a socket at every execution, because the CLI script is executed in a single process that starts, open a socket and ends (closing the socket along with the process).

In CGI mode with one process per script, this is also true.

With the Apache SAPI, it depends what type of multi-processing module (MPM) is in use. mpm-prefork spawns a new process at every request, so it most likely doesn't support it. mpm-worker however, spawns threads, so it will probably work there. mpm-winnt is a Windows variant of a multi-threaded MPM, so it should work too.

The worst that can happen is that the call will be executed as a normal fsockopen call.

like image 128
netcoder Avatar answered Nov 15 '22 11:11

netcoder