1

我正在尝试了解 PHP 中的套接字,并且大量阅读使我走上了stream_socket_server().

我使用类似于下面的代码在 linux 的两个终端之间进行了基本的聊天,并希望我的下一步是在网络上构建聊天或通知系统。

我期望发生的事情:

eventSource.html 中的事件侦听器将侦听 while 循环中的事件并输出从正在运行 server.php 的 linux 终端接收到的消息

怎么了:

从 eventSource.html 的角度来看,一切都在正常工作。因此,如果我要取消此操作的全部目的并仅将消息替换为标准字符串,那么它将每秒Hello World成功输出。<li>message:{Hello World}</li>

但是,一旦我尝试从终端读取数据,除了<li>message: {}</li>每秒之外,什么都没有出现。值得注意的是,当我运行 server.php 时,它会等待客户端,然后当我运行 eventSource.html 时,它会成功连接。

我误解了这是如何工作的?我假设在 while 循环中的每一秒它都会查找该流中的数据。

或者我在学习套接字方面走的是一条完全错误的道路。

server.php (我从 linux 的终端加载它)

<?php 
$PORT = 20226;          //chat port
$ADDRESS = "localhost"; //adress
$ssock;     //server socket
$csock;     //chat socket
$uin;       //user input file descriptor

$ssock = stream_socket_server("tcp://$ADDRESS:$PORT");      //creating the server sock

echo "Waiting for client...\n";
$csock = stream_socket_accept($ssock);          //waiting for the client to connect
                                        //$csock will be used as the chat socket
echo "Connection established\n";

$uin = fopen("php://stdin", "r");       //opening a standart input file stream

$conOpen = true;    //we run the read loop until other side closes connection
while($conOpen) {   //the read loop

    $r = array($csock, $uin);       //file streams to select from
    $w = NULL;  //no streams to write to
    $e = NULL;  //no special stuff handling
    $t = NULL;  //no timeout for waiting

    if(0 < stream_select($r, $w, $e, $t)) { //if select didn't throw an error
        foreach($r as $i => $fd) {  //checking every socket in list to see who's ready
            if($fd == $uin) {       //the stdin is ready for reading
                $text = fgets($uin);
                fwrite($csock, $text);
            }
            else {                  //the socket is ready for reading
                $text = fgets($csock);
                if($text == "") {   //a 0 length string is read -> connection closed
                    echo "Connection closed by peer\n";
                    $conOpen = false;
                    fclose($csock);
                    break;
                }
                echo "[Client says] " .$text;
            }
        }
    }
}

client.php 从下面的 eventSource.html 加载

<?php 

date_default_timezone_set("America/New_York");
header("Content-Type: text/event-stream\n\n");
$PORT = 20226;    //chat port
$ADDRESS = "localhost"; //adress

$sock = stream_socket_client("tcp://$ADDRESS:$PORT");
$uin = fopen("php://stdin", "r");

while (1) {
$text = fgets($uin);

  echo 'data: {'.$text.'}';
  echo "\n\n";


  ob_end_flush();
  flush();
  sleep(1);

}

事件源.html

<script>
    var evtSource = new EventSource("client.php");

    evtSource.onmessage = function(e) {
    var newElement = document.createElement("li");

  newElement.innerHTML = "message: " + e.data;
  var div = document.getElementById('events');
  div.appendChild(newElement);
}
</script>
<div id="events">
</div>
4

0 回答 0