php PHP套接字监听循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12999900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:37:58  来源:igfitidea点击:

PHP socket Listening loop

phpsocketsnetworkingtcp

提问by Dest

With the following code, I can receive 1 request and write it:

使用以下代码,我可以接收 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();

But it close automatically listening once it received 1 packet. I need to keep receiving packets until an exit or any close command is received.

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

How should I go about changing the code above to make this function into a loop?

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

回答by Dest

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;

If request will be exit listening will closed. That method was tested :) and it works.

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

回答by Asad Saeeduddin

How about:

怎么样:

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();