I'm very new to PHP so this might be something simple. Anyway, I'm trying to create 2-way communication between a PHP script (activated by a web client) and a local process (written in C开发者_JAVA百科++). The PHP script should send some information to the C++ process and then wait for a response. My problem is that the only way to set up this kind of communication seems to be to use socket_bind, but when I do, it fails with the 'address already in use' error. The socket file in question, /tmp/sock, has already been created by the C++ process, which is running continuously (it can not be launched by the PHP script). If I use socket_connect and just write something to the C++ process, that works just fine; but I need to bind before I can listen to that socket from the PHP script. Here's my code:
<?php
error_reporting(E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit(0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
//Adapted from http://www.php.net/manual/en/sockets.examples.php
if (($sock = socket_create(AF_UNIX, SOCK_STREAM,0)) === false)
{
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
if (socket_bind($sock, '/tmp/sock') === false) //Fails here
{
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
....
Thanks--
Your C++ and PHP codes have to mark the socket as shared (SO_REUSE_ADDR).
It turns out that what's needed is simply socket_read(). I didn't realize you could do both operations on the same socket (when it was merely connected and not bound). User hamishcool3 at PHP socket_read has a great utility function for reading from a socket until a particular character is reached (though it is probably slower than a standard byte-limited read).
精彩评论