【问题标题】:PHP socket Listening loopPHP套接字监听循环
【发布时间】:2023-03-09 12:27:01
【问题描述】:

使用以下代码,我可以接收 1 个请求并编写它:

function listen()
{
    // Set time limit to indefinite execution
    set_time_limit (0);

    // Set the ip and port we will listen on
    $address = 'XX.XX.XX.XXX';
    $port = XXXX;

    // Create a TCP Stream socket
    $sock = socket_create(AF_INET, SOCK_STREAM, 0);

    // Bind the socket to an address/port
    $bind = socket_bind($sock, $address, $port);

    // Start listening for connections
    socket_listen($sock);

    /* Accept incoming requests and handle them as child processes */
    $client = socket_accept($sock);

    // Read the input from the client – 1024 bytes
    $input = socket_read($client, 2024);

    // Strip all white spaces from input
    echo $input;

    // Close the master sockets
    $close = socket_close($sock);

    var_dump($close);
}

listen();

但它会在收到 1 个数据包后自动关闭侦听。我需要继续接收数据包,直到收到退出或任何关闭命令。

我应该如何更改上面的代码以使这个函数成为一个循环?

【问题讨论】:

    标签: php sockets networking tcp


    【解决方案1】:
    set_time_limit (0);
    
    $address = '46.49.41.188';
    
    $port = 7777;
    $con = 1;
    $word = "";
    
    $sock = socket_create(AF_INET, SOCK_STREAM, 0);
    $bind = socket_bind($sock, $address, $port);
    
    socket_listen($sock);
    
    while ($con == 1)
    {
        $client = socket_accept($sock);
        $input = socket_read($client, 2024);
    
        if ($input == 'exit') 
        {
            $close = socket_close($sock);
            $con = 0;
        }
    
        if($con == 1)
        {
            $word .= $input;
        }
    }
    
    echo $word;
    

    如果请求将退出侦听将关闭。该方法已经过测试:) 并且有效。

    【讨论】:

      【解决方案2】:

      怎么样:

      function listen(){
      // Set the ip and port we will listen on
      $address = 'XX.XX.XX.XXX';
      $port = XXXX;
      // Create a TCP Stream socket
      $sock = socket_create(AF_INET, SOCK_STREAM, 0);
      // Bind the socket to an address/port
      $bind = socket_bind($sock, $address, $port);
      // Start listening for connections
      socket_listen($sock);
      /* Accept incoming requests and handle them as child processes */
      $client = socket_accept($sock);
      // Read the input from the client – 1024 bytes
      $input = socket_read($client, 2024);
      // Strip all white spaces from input
      echo $input;
      // Close the master sockets
      $close = socket_close($sock);
      var_dump($close);
      listen();
      }
      set_time_limit (0);
      listen();
      

      【讨论】:

      • 首先感谢您的回答:)...我会尝试这个例子,但问题是:socket_close 不能快速关闭套接字。我有一个示例如何使我的代码进入循环。我会写那个代码。
      猜你喜欢
      • 1970-01-01
      • 2011-02-15
      • 2013-03-29
      • 2018-07-13
      • 2016-04-21
      • 2021-09-12
      • 1970-01-01
      • 2016-04-06
      • 2016-10-12
      相关资源
      最近更新 更多