简体   繁体   English

PHP:重新连接客户端套接字

[英]PHP: Reconnect client socket

I'm working on a php socket client script. 我正在研究一个php套接字客户端脚本。 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: 但是,我从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. 我尝试使用“unset”然后“socket_create”再次重新创建$ socket,但这也没有帮助。

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. 带有socket_write的那段代码是在一个单独的函数中。 I had added "global $socket" at the beginning of the function, but turns out I also needed to add it AFTER unset. 我在函数的开头添加了“global $ socket”,但事实证明我还需要在未设置之后添加它。 Also, to unset a global, I should be using unset($GLOBALS['socket']); 另外,要取消设置全局,我应该使用unset($ GLOBALS ['socket']); Thanks to EJP for making me re-examine this. 感谢EJP让我重新审视这一点。

You can't reconnect a socket. 您无法重新连接套接字。 You have to create a new one. 你必须创建一个新的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM