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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程