2014-01-09 71 views
2

我正在嘗試使用套接字在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程序) - 瀏覽器存儲。有沒有其他方法?

謝謝,保羅

+0

我試圖用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

回答

1

是,SSE(Server-Sent Event)是單向通信(http://www.w3schools.com/html/html5_serversentevents.asp。但是你可以用WebSocket API用於發送和接收數據(見`https://developer.mozilla.org/en-US/docs/Web/API/WebSocket)。

+0

是的,這是一個解決方案,但不是在我的情況,因爲我的數據傳輸是在外部Linux板上的網頁和C程序(它沒有websocket支持)之間,所以我不確定我是否可以使用像[libwebsockets](http:// libwebsockets .org/trac/libwebsockets) – PaulPonomarev

+0

@PaulPonomarev C程序和服務器如何交互? – voodoo417

+0

正如你在這裏看到的,通過TCP套接字。 C程序是一個非阻塞的服務器,他等待連接,並在連接時收到消息併發送答案 – PaulPonomarev