TCP client socket

suggest change

Creating a socket that uses the TCP (Transmission Control Protocol)

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

Make sure the socket is successfully created. The onSocketFailure function comes from http://stackoverflow.com/documentation/php/6138/sockets/23034/handling-socket-errors example in this topic.

if(!is_resource($socket)) onSocketFailure("Failed to create socket");

Connect the socket to a specified address

The second line fails gracefully if connection failed.

socket_connect($socket, "chat.stackoverflow.com", 6667)
        or onSocketFailure("Failed to connect to chat.stackoverflow.com:6667", $socket);

Sending data to the server

The socket_write function sends bytes through a socket. In PHP, a byte array is represented by a string, which is normally encoding-insensitive.

socket_write($socket, "NICK Alice\r\nUSER alice 0 * :Alice\r\n");

Receiving data from the server

The following snippet receives some data from the server using the socket_read function.

Passing PHP_NORMAL_READ as the third parameter reads until a \r/\n byte, and this byte is included in the return value.

Passing PHP_BINARY_READ, on the contrary, reads the required amount of data from the stream.

If socket_set_nonblock was called in prior, and PHP_BINARY_READ is used, socket_read will return false immediately. Otherwise, the method blocks until enough data (to reach the length in the second parameter, or to reach a line ending) are received, or the socket is closed.

This example reads data from a supposedly IRC server.

while(true) {
    // read a line from the socket
    $line = socket_read($socket, 1024, PHP_NORMAL_READ);
    if(substr($line, -1) === "\r") {
        // read/skip one byte from the socket
        // we assume that the next byte in the stream must be a \n.
        // this is actually bad in practice; the script is vulnerable to unexpected values
        socket_read($socket, 1, PHP_BINARY_READ);
    }

    $message = parseLine($line);
    if($message->type === "QUIT") break;
}

Closing the socket

Closing the socket frees the socket and its associated resources.

socket_close($socket);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents