Shutting down a socket in PHP

I created a cache server and client in php, no need to ask why, just for fun. The implementation works, but a problem occures every time when:

When I stop the running server process, after a client disconnects and trying to restart the server, the socket_bind throws an error, that the address is already in use. The client always closes connection after the data has been sent or recieved and when I check if the port is in use via sudo netstat, the port is not listed. The server looks like this:

public function run()
{
    $this->socket = $this->ioHandler->createServerSocket();
    while ($this->running) {

        while ($connection = @socket_accept($this->socket)) {
            socket_set_nonblock($connection);
            $this->maintainer->maintainBucket($this->bucket);
            $this->maintainer->checkBackup(time(), $this->bucket);
            try {
                $dataString = $this->ioHandler->readFromSocket($connection);
                $data = unserialize($dataString);
                ($this->actionHandler)($data, $this->bucket, $this->ioHandler, $connection);
            } catch (Exception $ex) {
                $this->ioHandler->writeToSocket($connection, self::NACK);
                $this->ioHandler->closeSocket($connection);
            }
        }
    }
}

I think the problem might be that the server shuts down via a simple ctrl+c or a start-stop-daemon --stop --pidfile and the socket is still open and there might be some automatized service that cleans up dead sockets. How can I properly shut down the server? Can I somehow terminate the process by sending an input via STDIN to kill the server socket? Or am I wrong on the issue? The full code is available on github: https://github.com/dude920228/php-cache

Upvotes: 0

Views: 1141

Answers (1)

Djengobarm
Djengobarm

Reputation: 398

Perhaps it's related to TIME_WAIT state. Long story short - socket_close() may close the socket, but there still may be data to send. Until the data is sent, the port will not be available.

More info is:

Upvotes: 1

Related Questions