Persistent local domain socket in php

The answers I found to this question (e.g. here , here , and here ) are all related to pfsockopen (), which seem to be oriented towards non-local socket connections. However, the code that I have written so far uses php to access the C ++ server through a local connection. I want this connection to be constant (so that I can use it for a comet, by the way). Here is my fickle version:

<?php session_start(); ... if (($sock = socket_create(AF_UNIX, SOCK_STREAM,0)) === false) { echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; exit(); } $sess_id = $_SESSION['sess_id']; $sock_str = '/tmp/sockdir/' . $sess_id; //The socket is named after the php session, not important if (socket_connect($sock, $sock_str) === false) { echo "socket_connect() to " . $sock_str . " failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n"; socket_close($sock); exit(); } $msg = $_GET['message']; // ... do things with $msg socket_close($sock); ?> 

Now I can’t just save '$ sock' as the $ _SESSION variable and just access it every time this script is called, I found. Any tips on what I can do to turn this into a permanent connection?

+4
source share
2 answers

As the links you provided, php is not a persistent language, and there is no way to have persistence in all sessions (i.e. page loading). You can create a middle platform by running the second php script as a daemon, and your main script (i.e. the one that the user gets into) connects to this (yes - through the socket ...) and receives data from it.

If you have to do this and want to avoid the hassel of Web Sockets, try the new HTML5 API EventStream , as it gives you the best of both worlds: the cometary infrastructure without the neglect of a long poll or the need for a dedicated web socket server.

+4
source

If you need to open the connection open, you need to leave the PHP script open. Typically, PHP is called and then closed after running the script (CGI, CLI) or is a mixture (mod_php in apache, FCGI), in which sometimes the PHP interpreter remains in memory after the script is completed (so that everything related to the OS for this process, will still remain as a socket descriptor).

However, this is never saved. Instead, you need to make a PHP daemon that can store your PHP scripts in memory. The existing solution for this is Appserver-In-PHP . It will save your code in memory until you restart the server. Like code, you can also store variables between requests, for example. connection handle.

+2
source

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


All Articles