更新时间:2023-11-17 23:08:46
我找到了解决方案.当我使用时,它似乎有效:
I found a solution. It seems to work, when I use:
$stdin = fopen('php://stdin', 'r');
$read = array($sock, $stdin);
$write = NULL;
$exept = NULL;
而不仅仅是标准输入.尽管 php.net 说,STDIN 已经打开并使用$stdin = fopen('php://stdin', 'r');好像不是,如果你想把它传给stream_select.此外,应该使用 $sock = fsockopen($host); 创建到服务器的套接字.而不是在客户端使用 socket_create ......必须喜欢这种语言,它的合理性和清晰的手册......
Instead of just STDIN. Despite php.net says, STDIN is already open and saves using $stdin = fopen('php://stdin', 'r'); It seems not, if you want to pass it into stream_select. Also, the socket to the server should be created with $sock = fsockopen($host); instead of using socket_create on the client side... gotta love this language and it's reasonability and clear manual...
这是一个使用 select 连接到回显服务器的客户端的工作示例.
Here a working example of a client that connects to an echo server using select.
<?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;
}
}
}
}