【问题标题】:Two way continuous socket communication两路连续套接字通信
【发布时间】: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


【解决方案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)。

【讨论】:

  • 是的,这是一个解决方案,但不是在我的情况下,因为我的数据传输是在外部 linux 板上的网页和 C 程序(不支持 websocket)之间进行的,所以我不确定是否我可以使用类似libwebsockets
  • @PaulPonomarev C 程序和服务器如何交互?
  • 正如您在此处看到的,通过 TCP 套接字。 C 程序是一个非阻塞服务器,它等待连接并在连接时接收消息并发送答案
猜你喜欢
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多