加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP套接字侦听循环

发布时间:2020-12-13 13:16:00 所属栏目:PHP教程 来源:网络整理
导读:使用以下代码,我可以收到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 =
使用以下代码,我可以收到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个数据包就会自动收听.我需要继续接收数据包,直到收到退出或任何关闭命令.

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

set_time_limit (0);

$address = '46.49.41.188';

$port = 7777;
$con = 1;
$word = "";

$sock = socket_create(AF_INET,0);
$bind = socket_bind($sock,$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;

如果请求将退出监听将关闭.该方法已经过测试:)并且可行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读