我正在尝试学习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);
}
eventSource.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>