大家好,你好吗? 请问我有这个将XML数据发送到网络的网络设备,因此我目前正在开发一个监控应用程序,该应用程序将永久连接到该设备以接收XML数据,只要该设备不断将数据发送到网络连接的那一刻。
我已经使用了php套接字编程,我的应用程序连接到服务器,因为它不断发送xml数据,但是我已经尝试找到一种方法来发送XML数据,一旦它循环通过,只在设备发送时重新发送发送另一个,但它没有那样工作。以下是代码:
<?php
//timeout limit
set_time_limit(0);
//Creating Socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error($socket)) . "<br />";
} else {
echo "OK.<br />";
}
echo "Attempting to connect to the socket'...";
$result = socket_connect($socket, '192.168.43.50', 10001);
if ($result === false) {
echo "socket_connect() failed.<br />Reason: ($result) " . socket_strerror(socket_last_error($socket)) . "<br />";
} else {
echo "OK.<br />";
}
$in = "GET / HTTP/1.1\r<br />";
$in .= "Host: 192.168.43.50\r\n<br />";
$in .= "Content-Type: application/xml; encoding=UTF-8\r\n";
$in .= "Accept: application/xml\n";
$in .= "Connection: Close\r<br />\r<br />";
$out= '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.<br />";
echo "Reading response:<br /><br />";
while ($out = socket_read($socket, PHP_BINARY_READ g)) {
//$result= simplexml_load_string($out) or die ("Error: Cannot create object");
//print_r ($result);
echo htmlspecialchars ($out)."\r\n /<br /><br />";
echo "Closing socket...";
socket_close($socket);
echo "OK.<br /><br />";
?>
我使用了fsocket,我也像想要的那样收到了XML,但连接终止了,我不能不断地接收XML数据。 继承人的代码
<?php
$fp = fsockopen("192.168.43.50", 10001, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)";
} else {
$wait = true;
$out = '<?xml version="1.0" encoding="UTF-8"?>';
// [1] disable blocking
stream_set_blocking($fp, 0);
fwrite($fp, $out);
while (!feof($fp)) {
$r = fgets($fp);
echo htmlspecialchars ($r);
if (!strcmp($r, "")){
if (!$wait) {
// [2] has recieved data on this socket before
break;
}
} else {
$wait = false;
}
}
fclose($fp);
}
?>