将php流套接字与eventSource相结合
我正在努力学习PHP中的套接字,大量阅读使我走上了将php流套接字与eventSource相结合,php,sockets,eventsource,Php,Sockets,Eventsource,我正在努力学习PHP中的套接字,大量阅读使我走上了stream\u socket\u server()的道路 我在linux的两个终端之间进行了一次基本的聊天,使用的代码与下面类似,我希望下一步是在web上构建聊天或通知系统 我预期会发生什么: eventSource.html中的事件侦听器将侦听while循环中的事件,并输出从运行server.php的linux终端接收到的消息 发生了什么: 从eventSource.html的角度来看,一切都正常工作。因此,如果我取消了它的全部用途,只是用一
stream\u socket\u server()
的道路
我在linux的两个终端之间进行了一次基本的聊天,使用的代码与下面类似,我希望下一步是在web上构建聊天或通知系统
我预期会发生什么:
eventSource.html中的事件侦听器将侦听while循环中的事件,并输出从运行server.php的linux终端接收到的消息
发生了什么:
从eventSource.html的角度来看,一切都正常工作。因此,如果我取消了它的全部用途,只是用一个标准字符串替换消息,Hello World
,那么它将每秒成功地输出消息:{Hello World}
但是,一旦我尝试从终端读取数据,除了每隔一秒钟出现一条消息:{}外,什么也没有出现。值得注意的是,当我运行server.php时,它会等待客户端,然后当我运行eventSource.html时,它会成功连接
我误解了这是怎么回事?我假设while循环中的每一秒都会查找该流中的数据
还是我在学习上走了一条完全错误的道路
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;
}
}
}
}
<?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);
}
<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>