【发布时间】:2014-01-27 15:44:05
【问题描述】:
我正在尝试使用套接字编写 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,所以我在 index.html 和
if(isset($_POST["text"])){send("Value posted"); $_SESSION["text"] = $_POST["text"];} if(isset($_SESSION["text"])){send("Session started"); $text = $_SESSION["text"];}中添加了$.post("socket/SSE.php", {text: counter});。但是现在 SSE 一直在写入一个值,尽管“计数器”是递增变量
标签: javascript php sockets jquery server-sent-events