我正在嘗試使用套接字在C程序和網頁之間編寫連續通信。我已經得到了建議here在網頁上使用SSE。但是SSE是一種單向交流。所以,我試圖通過jquery.post發佈數據雙向連續套接字通信
使用Javascript(index.html的):
function update_content() {
var sse = new EventSource("socket/SSE.php");
sse.onmessage = function(e) {
$.post("socket/SSE.php", {text: "Hello World!"});
console.log(e.data);
};
}
update_content();
PHP(SSE.php):
<?php
function send($data){
echo "id: ".time().PHP_EOL;
echo "data: ".$data.PHP_EOL;
echo PHP_EOL;
ob_flush(); // clear memory
flush();
}
header('Content-Type: text/event-stream'); // specific sse mimetype
header('Cache-Control: no-cache'); // no cache
$address='localhost';$port=5001;
while(true){
$msg=($sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP))?'created':'error';
//send("Socket creation: ".$msg);
$msg=($ret = socket_connect($sock, $address, $port))?'connected':'refused';
//send("connection: ".$msg);
$text = $_POST["text"];
send("Trying to write $text");
$msg = (false === socket_write($sock, $text, strlen($text)))?"Error":"Success";
//send($msg);
$msg = (false === ($buf = socket_read($sock, 1024)))?'Error':'Success!';
send($buf);
sleep(2);
}
,當然,它沒不起作用,因爲網頁只有在$ .post函數調用時纔有$ _POST數據。我只看到一個解決方案將參數發送到SSE.php(並進一步發送到C程序) - 瀏覽器存儲。有沒有其他方法?
謝謝,保羅
我試圖用sessionStorage的,所以我說'$ .post(「socket/SSE.php」,{text:counter});'給index.html和'if(isset($ _ POST [「text」])){send(「Value posted」); $ _SESSION [「text」] = $ _POST [「text」];} if(isset($ _ SESSION [「text」])){send(「Session started」); $ text = $ _SESSION [「text」]; }'但現在SSE一直在寫一個值,雖然「counter」是遞增的變量 – PaulPonomarev