Reputation: 14815
I have a client-server application, in which the server may require to send information back to clients.
As the client-server pattern does not allow the server to "request" the client, there are 2 solutions:
Currently, the client (Web app with JavaScript and Html/Css) open a streaming connection to the server (A C++ server) which may send information back to the client.
I would like to implement a PHP version of this feature to allow low-cost hosting to work with my program (low-cost hosting usually does not provide access to install/run binaries). The idea is that the client make a request that establish the streaming socket, it save the socket and then, an other request may retrieve this socket and send new information through it.
So, my question is: How to save an http socket in PHP, so a further request may retrieve it?
I do not know even if that is possible, I read about pfsockopen, but it seem a bit different to what I need ( I may be wrong ).
Upvotes: 3
Views: 1542
Reputation: 14982
So, you need two connections for each client, one persist for get data from server, and other to send data to.
Something like:
in persist.php:
$socket = stream_socket_server('unix:///tmp/unique.sock', $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
$buffer = "";
// Read until double CRLF
while( !preg_match('/\r?\n\r?\n/', $buffer) )
$buffer .= fread($client, 2046);
//Operate with our listener
echo $buffer;
flush();
// Respond to socket client
fwrite($conn, "200 OK HTTP/1.1\r\n\r\n");
fclose($conn);
}
fclose($socket);
}
in senddata.php:
$sock = stream_socket_client('unix:///tmp/unique.sock', $errno, $errstr);
fwrite($sock, $data);
fflush($sock);
fclose($sock);
Upvotes: 1
Reputation: 14982
One way to solve it - forget about sockets
.
Pseudocode:
// receive request, set some session_id if not exists
// request contains last_timestamp, so we know which data client already have
// check have we any dataset for this session_id after last_timestamp
// return this dataset, or no_new_data signature
Data can be stored in database, for example.
Upvotes: 0