这个想法是通过TCP套接字连接PHP网页和C程序,网页等待C程序的连接并在连接建立后立即接收数据。PHP socket连接和数据接收代码如下:
PHP(socketRead.php):
$address = 'localhost';
$port = 5001;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
echo "Socket creation error";
}
else {
echo "Socket created <br/>";
}
if (($ret = socket_bind($sock, $address, $port)) < 0) {
echo "Host/port connection failed";
}
else {
echo "Host/port connection successful <br/>";
}
if (($ret = socket_listen($sock, 5)) < 0) {
echo "Socket error";
}
else {
echo "Waiting connection <br/>";
}
if (($msgsock = socket_accept($sock)) < 0) {
echo "Socket connection start error";
} else {
echo "Awaiting data <br/>";
}
//Connection established, reading data
if (false === ($buf = socket_read($msgsock, 1024))) {
echo "Read error";
} else {
echo "Data: ".$buf;
}
if (isset($sock)) {
socket_close($ret);
socket_close($sock);
}
echo "<br /> Socket closed";
要从套接字动态读取数据,我使用 jquery 请求。
Javascript(索引.html):
function update_content() {
var request = $.get("socket/socketRead.php");
request.success(function(result) {
document.write(result);
});
}
update_content();
在我尝试添加间隔以重复读取数据之前效果很好。
Javascript(索引.html):
var timer = setInterval(function(){update_content();}, 1000);
第一次连接/接收仍然有效,但是当我再次尝试连接时,我在 C 程序中收到“连接被拒绝”。你能帮我解决这个问题吗?