XCIV. Socket functions

Ostrze¿enie

Ten moduł jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie tych funkcji, ich nazwy, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tego modułu na własne ryzyko.

The socket extension implements a low-level interface to the socket communication functions, providing the possibility to act as a socket server as well as a client.

The socket functions described here are part of an extension to PHP which must be enabled at compile time by giving the --enable-sockets option to configure.

For a more generic client-side socket interface, see fsockopen() and pfsockopen().

When using these functions, it is important to remember that while many of them have identical names to their C counterparts, they often have different declarations. Please be sure to read the descriptions to avoid confusion.

That said, those unfamiliar with socket programming can still find a lot of useful material in the appropriate Unix man pages, and there is a great deal of tutorial information on socket programming in C on the web, much of which can be applied, with slight modifications, to socket programming in PHP.

Przykład 1. Socket example: Simple TCP/IP server

This example shows a simple talkback server. Change the address and port variables to suit your setup and execute. You may then connect to the server with a command similar to: telnet 192.168.1.53 10000 (where the address and port match your setup). Anything you type will then be output on the server side, and echoed back to you. To disconnect, enter 'quit'.

#!/usr/local/bin/php -q
<?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 ();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 0) {
    echo "socket_create() failed: reason: " . socket_strerror ($sock) . "\n";
}

if (($ret = socket_bind ($sock, $address, $port)) < 0) {
    echo "socket_bind() failed: reason: " . socket_strerror ($ret) . "\n";
}

if (($ret = socket_listen ($sock, 5)) < 0) {
    echo "socket_listen() failed: reason: " . socket_strerror ($ret) . "\n";
}

do {
    if (($msgsock = socket_accept($sock)) < 0) {
        echo "socket_accept() failed: reason: " . socket_strerror ($msgsock) . "\n";
        break;
    }
    /* Send instructions. */
    $msg = "\nWelcome to the PHP Test Server. \n" .
        "To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    socket_write($msgsock, $msg, strlen($msg));

    do {
        if (FALSE === ($buf = socket_read ($msgsock, 2048))) {
            echo "socket_read() failed: reason: " . socket_strerror ($ret) . "\n";
            break 2;
        }
        if (!$buf = trim ($buf)) {
            continue;
        }
        if ($buf == 'quit') {
            break;
        }
        if ($buf == 'shutdown') {
            socket_close ($msgsock);
            break 2;
        }
        $talkback = "PHP: You said '$buf'.\n";
        socket_write ($msgsock, $talkback, strlen ($talkback));
        echo "$buf\n";
    } while (true);
    socket_close ($msgsock);
} while (true);

socket_close ($sock);
?>

Przykład 2. Socket example: Simple TCP/IP client

This example shows a simple, one-shot HTTP client. It simply connects to a page, submits a HEAD request, echoes the reply, and exits.

<?php
error_reporting (E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port = getservbyname ('www', 'tcp');

/* Get the IP address for the target host. */
$address = gethostbyname ('www.php.net');

/* Create a TCP/IP socket. */
$socket = socket_create (AF_INET, SOCK_STREAM, 0);
if ($socket < 0) {
    echo "socket_create() failed: reason: " . socket_strerror ($socket) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect ($socket, $address, $service_port);
if ($result < 0) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
} else {
    echo "OK.\n";
}

$in = "HEAD / HTTP/1.0\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write ($socket, $in, strlen ($in));
echo "OK.\n";

echo "Reading response:\n\n";
while ($out = socket_read ($socket, 2048)) {
    echo $out;
}

echo "Closing socket...";
socket_close ($socket);
echo "OK.\n\n";
?>

Spis treści
socket_accept -- Accepts a connection on a socket
socket_bind -- Binds a name to a socket
socket_close -- Closes a socket descriptor
socket_connect -- Initiates a connection on a socket
socket_listen -- Listens for a connection on a socket
socket_read -- Reads from a socket
socket_create -- Create a socket (endpoint for communication)
socket_strerror -- Return a string describing a socket error
socket_write -- Write to a socket
socket_fd_alloc -- Allocates a new file descriptor set
socket_fd_free -- Deallocates a file descriptor set
socket_fd_set -- Adds (a) file descriptor(s) to a set
socket_fd_clear -- Clears (a) file descriptor(s) from a set
socket_fd_isset -- Checks to see if a file descriptor is set within the file descrirptor set
socket_fd_zero -- Clears a file descriptor set
socket_select -- Runs the select() system call on the sets mentioned with a timeout specified by tv_sec and tv_usec
socket_create_listen -- Opens a socket on port to accept connections
socket_set_nonblock -- Sets nonblocking mode for file descriptor fd
socket_getsockname -- Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the local side of a socket
socket_getpeername -- Given an fd, stores a string representing sa.sin_addr and the value of sa.sin_port into addr and port describing the remote side of a socket
socket_iovec_alloc -- ...]) Builds a 'struct iovec' for use with sendmsg, recvmsg, writev, and readv
socket_iovec_fetch -- Returns the data held in the iovec specified by iovec_id[iovec_position]
socket_iovec_set -- Sets the data held in iovec_id[iovec_position] to new_val
socket_iovec_add -- Adds a new vector to the scatter/gather array
socket_iovec_delete -- Deletes a vector from an array of vectors
socket_iovec_free -- Frees the iovec specified by iovec_id
socket_readv -- Reads from an fd, using the scatter-gather array defined by iovec_id
socket_writev -- Writes to a file descriptor, fd, using the scatter-gather array defined by iovec_id
socket_recv -- Receives data from a connected socket
socket_send -- Sends data to a connected socket
socket_recvfrom -- Receives data from a socket, connected or not
socket_sendto -- Sends a message to a socket, whether it is connected or not
socket_recvmsg -- Used to receive messages on a socket, whether connection-oriented or not
socket_sendmsg -- Sends a message to a socket, regardless of whether it is connection-oriented or not
socket_getopt -- Gets socket options for the socket
socket_setopt -- |array optval) Sets socket options for the socket
socket_create_pair -- Creates a pair of indistinguishable sockets and stores them in fds.
socket_shutdown -- Shuts down a socket for receiving, sending, or both.
socket_last_error -- Returns/Clears the last error on the socket