rbarnes' tip is helpful, but I found that I needed to add a check for SOCKET_EISCONN in the while loop:
...
$error = socket_last_error();
if ($error == SOCKET_EISCONN) {
$connected = true;
break;
}
...
At least on Mac OS X 10.5.