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

时间:2013-07-07 21:05:50

标签: php apache drupal p2p

我有两个基于LAMP(使用Drupal CMS)的网站,我想在服务器之间进行通信。作为示例,网站1上的客户端执行一些活动,数据和内容被传送到网站2,网站2处理数据/请求并且响应回网站1客户端。我怎样才能做到这一点 ?是否有任何库或模块来实现这一目标?我从哪里开始构建这样的功能?

1 个答案:

答案 0 :(得分:1)

你想做什么,可以使用POST查询通过HTTP协议使用套接字来完成。

例如,存在从服务器A到服务器B的通信。注意:您可以将其设置为双向。

HTTP QUERY(客户端)

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