socket_create_pair
socket_create_pair
Creates a pair of indistinguishable sockets and stores them in an array
bool **socket_create_pair** int $domain int $type int $protocol array $pair
creates two connected and
indistinguishable sockets, and stores them in .
This function is commonly used in IPC (InterProcess Communication).
socket_create_pair``pair
domain
The parameter specifies the protocol
family to be used by the socket. See
for the full list.
domain``socket_create
type
The parameter selects the type of communication
to be used by the socket. See for the
full list.
type``socket_create
protocol
The parameter sets the specific
protocol within the specified to be used
when communicating on the returned socket. The proper value can be retrieved by
name by using . If
the desired protocol is TCP, or UDP the corresponding constants
, and
can also be used.
protocol``domain``getprotobyname``SOL_TCP``SOL_UDP
See for the full list of supported
protocols.
`socket_create`
pair
Reference to an array in which the two instances will be inserted.
Socket
return.success
Voorbeeld: example
<?php
$sockets = array();
/* On Windows we need to use AF_INET */
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);
/* Setup socket pair */
if (socket_create_pair($domain, SOCK_STREAM, 0, $sockets) === false) {
echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Receive Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {
echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);
/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>
Voorbeeld: IPC example
<?php
$ary = array();
$strone = 'Message From Parent.';
$strtwo = 'Message From Child.';
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary) === false) {
echo "socket_create_pair() failed. Reason: ".socket_strerror(socket_last_error());
}
$pid = pcntl_fork();
if ($pid == -1) {
echo 'Could not fork Process.';
} elseif ($pid) {
/*parent*/
socket_close($ary[0]);
if (socket_write($ary[1], $strone, strlen($strone)) === false) {
echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[1]));
}
if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) {
echo "Received $strtwo\n";
}
socket_close($ary[1]);
} else {
/*child*/
socket_close($ary[1]);
if (socket_write($ary[0], $strtwo, strlen($strtwo)) === false) {
echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[0]));
}
if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) {
echo "Received $strone\n";
}
socket_close($ary[0]);
}
?>
socket_create``socket_create_listen``socket_bind``socket_listen``socket_last_error``socket_strerror