在后端/异步启动纯PHP套接字

时间:2015-06-01 03:31:55

标签: php sockets asynchronous

  

我为我的ios应用程序创建了一个php套接字。当我在完成所有工作之前使用终端启动它时,它工作正常。

     

问题是第一个 socket_write。

在编写之前,请检查服务器的套接字是否正在运行.. $result = socket_connect($socket, $address, $service_port);

如果false我需要重定向到页面http://localhost/api3/server.php以启动套接字

public function __socket_write($text)
{
    $result = socket_connect($socket, $address, $service_port);

    if ($result === false) 
    {
        // if failed to connect means the server is currently down/not running
        $this->__socket_start("http://localhost/api3/server.php");
    }
    // codes here not called api got an time out error as well, must have been    redirected completely?
}

public function __socket_start($url, $status_code = 303)
{
   header('Location: '.$url, true, $status_code);
}

服务器已成功启动,但看起来我需要异步调用__socket_start()才能执行$this->__socket_start()以下的代码,但我不知道怎么做,过了一会儿服务器再次关闭......

当我使用终端php server.php启动套接字时,它不会断开连接。

提前谢谢你......

1 个答案:

答案 0 :(得分:0)

解决了这个问题,它不是我真正想做的那个,但它现在正常工作,就像我从一开始就打算做的那样......

以下是我现在的样子:

public function __socket_write($text)
{
    $service_port = xxxxxx;

    $address = MyAddress;

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

    $result = socket_connect($socket, $address, $service_port);

    if ($result === false) 
    {
        $this->__socket_start();
    } 

    @socket_listen($socket);

    ...

    socket_close($socket);
}

public function __socket_start()
{
    $cmd = "php server.php";

    shell_exec($cmd." > /dev/null 2>/dev/null &");
}