服务器到服务器的实时通信


server to server real-time communiation

我有两个基于LAMP(使用Drupal CMS)的网站,我想在服务器之间进行通信。例如,网站1上的客户端执行一些活动,数据和内容被传送到网站2,网站2处理数据/请求并回复网站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 HANDLER(服务器)

# 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.";