I'm doing:
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (@socket_connect($socket, $path) === false) { ... }
But I get this error:
(91): Protocol wrong type for socket
Am I using any of the parameters wrong? I suspect from the second socket_create parameter. I could't find any help in the documentation: http://php.net/manual/es/function.socket-create.php
It's maby outdated, but I've found that this way it works properly:
$sock = stream_socket_client('unix:///tmp/test.sock', $errno, $errst);
fwrite($sock, 'message');
$resp = fread($sock, 4096);
fclose($sock);
For Unix sockets we don't need to use socket_connect
.
Here is a very simple working example with a sender and a receiver:
sender.php
<?php
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
socket_sendto($socket, "Hello World!", 12, 0, "/tmp/myserver.sock", 0);
echo "sent\n";
?>
receiver.php
<?php
$file = "/tmp/myserver.sock";
unlink($file);
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (socket_bind($socket, $file) === false) {
echo "bind failed";
}
if (socket_recvfrom($socket, $buf, 64 * 1024, 0, $source) === false) {
echo "recv_from failed";
}
echo "received: " . $buf . "\n";
?>
Note that only the receiver needs to bind to an address (the unix socket file) and then use socket_recvfrom
. The sender just calls socket_sendto
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With