Php – How to keep a Php stream_socket alive

PHPtcp

I have a Php application using stream_socket_client(), to get data through tcp from a back-end server, but would like to keep the connections alive or even better in a pool or something to avoid the connect/disconnect over head.

But I'm not a Php guru, so I have no idea how to do this. And although I could probably figure it out in a few hours, my time will be probably better spent picking on everyone's brains, so any advice?

Best Answer

Setting the STREAM_CLIENT_PERSISTENT flag upon stream creation prevents the connection from idling out. Internally, the flag makes stream_socket_client() call pfsockopen() (doc) instead of fsockopen() (doc).

The connection persistence is limited to the server process the connection was opened on. When your script ends, and you call it again, there may be no guarantee that the same process handles your request - another connection will be opened in this case. Putting the connection into $_SESSION to share it will not work.