我正在尝试使用套接字编写 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 程序)的解决方案 - 浏览器存储。还有其他办法吗?
谢谢,保罗
最佳答案
是的,SSE(Server-Sent Event)
是一种单向通信 ( http://www.w3schools.com/html/html5_serversentevents.asp 。但是您可以使用 WebSocket API
发送和接收数据(请参阅` https://developer.mozilla.org/en-US/docs/Web/API/WebSocket ).
关于javascript - 双向连续套接字通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21014321/