Trevor Forentz
Trevor Forentz

Reputation: 147

PHP: Reconnect client socket

I'm working on a php socket client script. I want the script to be able to handle server downtime.

I start the connection as follows

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

function connect()
{
    global $socket;
    global $ip;
    global $port;
    $connected = FALSE;
    while( $connected === FALSE )
    {
        sleep(5);
        $connected = socket_connect($socket, $ip, $port);
    }
}

connect();

which attempts connections until the server is available.

Further down, I detect that the server is not responding anymore, disconnect the socket, and try to reconnect to the server.

$ret = socket_write($socket, $str, strlen($str));
if ($ret === false)
{
    socket_shutdown($socket, 2);
    socket_close($socket);
    connect();
}

however, I get the following error from socket_connect:

A connect request was made on an already connected socket.

At this point, even if the server comes back online, the only way for my script to reconnect is by killing it and starting it up again. Is there more to shutting down a client-side socket connection? Most of what I've been able to find on the topic deals with sockets which listen for an incoming connection.

I've tried recreating $socket again using "unset" followed by "socket_create", but that hasn't helped either.

EDIT: What I mean is if I change that last chunk of code to the following

$ret = socket_write($socket, $str, strlen($str));
if ($ret === false)
{
    socket_shutdown($socket, 2);
    socket_close($socket);
    unset($socket);
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    connect();
}

then I still getting the same error.

Any help would be greatly appreciated.

SOLVED: Turns out this is really a global variable unset problem. That chunk of code with socket_write was in a separate function. I had added "global $socket" at the beginning of the function, but turns out I also needed to add it AFTER unset. Also, to unset a global, I should be using unset($GLOBALS['socket']); Thanks to EJP for making me re-examine this.

Upvotes: 0

Views: 2415

Answers (1)

user207421
user207421

Reputation: 310869

You can't reconnect a socket. You have to create a new one.

Upvotes: 2

Related Questions