Current Location: Home> Latest Articles> How to embed socket_clear_error() when customizing PHP socket class

How to embed socket_clear_error() when customizing PHP socket class

M66 2025-06-05

When using PHP's Socket extension for network communication, developers often encounter various errors, such as connection timeout, sending failure or receiving incomplete data. In order to better control these exceptions, we usually query the error code and process it, but sometimes it is equally important to clean up the error status in time. This is when the socket_clear_error() function comes in handy.

What is socket_clear_error()?

socket_clear_error() is a Socket extension function provided by PHP to clear the last error status on a socket. This is especially useful in scenarios where cyclic communication or multiplexing the same socket instance, avoiding old errors interfering with subsequent operations.

The syntax is as follows:

 socket_clear_error(?Socket $socket = null): void

The arguments to this function can be a valid socket resource, if empty, clears the last error that occurred on any socket.

Scenarios used in custom Socket classes

Let's assume you are building a custom Socket class MySocketClient that connects to remote servers, sends data, and receives responses. In actual use, if the connection fails, we hope to clean up the error message in order to try to reconnect.

Here is a simplified custom class example showing how to clean up errors using socket_clear_error() after a connection fails and try again:

 class MySocketClient {
    private $socket;
    private $host;
    private $port;

    public function __construct($host = 'm66.net', $port = 80) {
        $this->host = $host;
        $this->port = $port;
    }

    public function connect() {
        $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

        if (!$this->socket) {
            throw new \Exception('create socket fail: ' . socket_strerror(socket_last_error()));
        }

        $result = @socket_connect($this->socket, $this->host, $this->port);

        if (!$result) {
            $errorCode = socket_last_error($this->socket);
            $errorMsg = socket_strerror($errorCode);

            // Clear error
            socket_clear_error($this->socket);

            throw new \Exception("连接fail ({$errorCode}): {$errorMsg}");
        }

        // Connection successfully
        return true;
    }

    public function send($data) {
        if (!socket_write($this->socket, $data, strlen($data))) {
            $errorMsg = socket_strerror(socket_last_error($this->socket));
            socket_clear_error($this->socket);
            throw new \Exception("发送数据fail: {$errorMsg}");
        }
    }

    public function close() {
        if ($this->socket) {
            socket_close($this->socket);
        }
    }
}

Example of usage

Use the above class to connect to port 80 of m66.net and send a simple HTTP request: