5

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?

Robert Gould
  • 68,773
  • 61
  • 187
  • 272

1 Answers1

8

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.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Could you use server process pooling as a cheap way into a "kind-of" connection pooling? In terms of "Let there be one connection per process, and what process runs your script to becomes irrelevant."? – Tomalak Oct 28 '08 at 07:37
  • Maybe... not sure how to do that right now, but may look into it – Robert Gould Oct 28 '08 at 09:05
  • 4
    Should one call fclose() on the socket when using STREAM_CLIENT_PERSISTENT? – ColinM Jan 29 '13 at 15:47