繁体   English   中英

两路连续插座通讯

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM