我有两个基于 LAMP(使用 Drupal CMS)的网站,我想在服务器之间执行通信。例如,网站 1 上的客户端执行一些活动,数据和内容被传送到网站 2,网站 2 处理数据/请求并响应网站 1 客户端。我怎样才能做到这一点 ?是否有任何库或模块可以实现这一目标?我从哪里开始构建这样的功能?
问问题
60 次
1 回答
1
您想要做的事情,可以通过使用 POST 查询的 HTTP 协议使用套接字来完成。
例如,有一个从服务器 A 到服务器 B 的通信。注意:你可以让它双向。
HTTP 查询(客户端)
# the target url (without http://) or address of the remote host
# if the remote address is an ipv6 she must start and end with [] like this [::1].
$http_host = "website1.com"; # api.website1.com or localhost or 13.33.33.37
# The address of the script who's give answer from the root directory "/".
$script_path = "/answer.php";
# The parameters.
$http_params = "cost=156&product=" . urlencode("string must be url encoded");
$http_query = "POST " . $script_path . " HTTP/1.0" . "\r\n";
$http_query .= "Host: " . $http_host . "\r\n";
$http_query .= "Content-Type: application/x-www-form-urlencoded;" . "\r\n";
$http_query .= "Content-Length: ".strlen($http_params) . "\r\n";
$http_query .= "User-Agent: Drupal/PHP" . "\r\n\r\n";
$http_query .= $http_params;
$http_answer = NULL;
if ($socket = @fsockopen($http_host, 80, $errno, $errstr, 10))
{
fwrite($socket, $http_query);
while (!feof($socket))
$http_answer .= fgets($socket, 1024);
fclose($socket);
}
$http_answer = explode("\r\n", $http_answer);
if (is_array($http_answer))
{
echo "<pre>";
print_r($http_answer);
echo "</pre>";
}
只要有一点想象力,您就可以构建非常棒的工具:谷歌自己使用这种方式来生成关于 reCAPTCHA 的挑战。
HTTP 处理程序(服务器)
# if the parameters are matched.
if (isset($_POST['cost'], $_POST['product']))
{
# some treatement on the data
if (is_numeric($_POST['cost']))
echo "The cost were defined to $_POST[cost]" . "\r\n";
else
echo "The cost attribute must be a numerical value." . "\r\n";
if (!is_numeric($_POST['product']))
echo "The product were correctly registered." . "\r\n";
else
echo "The product attribute must be different than a numerical value." . "\r\n";
}
# otherwise the parameters are wrong.
else echo "Something went wrong.";
于 2013-07-08T03:12:10.913 回答