duanlanzhi5509 2013-04-26 22:04
浏览 28
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • doumeikuan6834 2013-04-26 23:42
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看