PHP TCP client socket
Creating a socket that uses the TCP (Transmission Control Protocol)
Make sure the socket is successfully created. The onSocketFailure function comes from Handling socket errors example in this topic.
Connect the socket to a specified address. The second line fails gracefully if connection failed. socket_connect($socket, "chat.stackoverflow.com", 6667) or
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.
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.
Closing the socket
Closing the socket frees the socket and its associated resources.