PHP:从套接字或 STDIN 读取

fda*_*fda 3 php stdin stream

我正在学习 PHP 中的套接字编程,因此我正在尝试一个简单的回显聊天服务器。

我写了一个服务器并且它可以工作。我可以将两个网络猫连接到它,当我在一个网络猫中写入时,我会在另一个网络猫上收到它。现在,我想在 PHP 中实现 NC 的功能

我想使用 Stream_select 来查看 STDIN 或套接字上是否有数据,以便将消息从 STDIN 发送到服务器或从服务器读取传入消息。不幸的是,php 手册中的示例没有给我任何如何做到这一点的线索。我尝试简单地 $line = fgets(STDIN) 和 socket_write($socket, $line) 但它不起作用。所以我开始往下走,只是想让stream_select在用户输入消息时起作用。

$read = array(STDIN);
$write = NULL;
$exept = NULL;

while(1){

    if(stream_select($read, $write, $exept, 0) > 0)
        echo 'read';
}
Run Code Online (Sandbox Code Playgroud)

给予

PHP 警告:stream_select():第 18 行 /home/user/client.php 中没有传递流数组

但是当我 var_dump($read) 时,它告诉我,它是一个带有流的数组。

array(1) {
  [0]=>
  resource(1) of type (stream)
}
Run Code Online (Sandbox Code Playgroud)

如何让stream_select工作?


PS:在Python中我可以做类似的事情

r,w,e = select.select([sys.stdin, sock.fd], [],[])
for input in r:
    if input == sys.stdin:
        #having input on stdin, we can read it now
    if input == sock.fd
        #there is input on socket, lets read it
Run Code Online (Sandbox Code Playgroud)

我在 PHP 中也需要同样的东西

fda*_*fda 5

我找到了解决方案。当我使用时,它似乎有效:

$stdin = fopen('php://stdin', 'r');
$read = array($sock, $stdin);
$write = NULL;
$exept = NULL;
Run Code Online (Sandbox Code Playgroud)

而不仅仅是 STDIN。尽管 php.net 说,STDIN 已经打开并使用 $stdin = fopen('php://stdin', 'r'); 保存。似乎不是,如果你想将它传递给stream_select。此外,应使用 $sock = fsockopen($host); 创建服务器的套接字。而不是在客户端使用 socket_create...我一定喜欢这种语言,它的合理性和清晰的手册...

这是使用 select 连接到 echo 服务器的客户端的工作示例。

<?php
$ip     = '127.0.0.1';
$port   = 1234;

$sock = fsockopen($ip, $port, $errno) or die(
    "(EE) Couldn't connect to $ip:$port ".socket_strerror($errno)."\n");

if($sock)
    $connected = TRUE;

$stdin = fopen('php://stdin', 'r'); //open STDIN for reading

while($connected){ //continuous loop monitoring the input streams
    $read = array($sock, $stdin);
    $write = NULL;
    $exept = NULL;

    if (stream_select($read, $write, $exept, 0) > 0){
    //something happened on our monitors. let's see what it is
        foreach ($read as $input => $fd){
            if ($fd == $stdin){ //was it on STDIN?
                $line = fgets($stdin); //then read the line and send it to socket
                fwrite($sock, $line);
            } else { //else was the socket itself, we got something from server
                $line = fgets($sock); //lets read it
                echo $line;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)