[英]Two way continuous socket communication
我正在嘗試使用套接字編寫C程序和網頁之間的持續通信。 我已經在這里獲得了在網頁上使用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 / zh-CN / docs / Web / API / WebSocket )。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.