【linux + lighttpd + php + zeromq】之實戰訓練一

微笑三、實踐

    1.helloworld(碼農的無敵測試程序)
           測試環境說明:
             1) 客戶端:ZeroMQ for PHP
             2) 服務端:ZeroMQ for C
           客戶端代碼:zmq-client.php
                 版權說明:此代碼是ZMQ官網測試代碼,可能做了一點修改;
                 運行說明:此處默認您已經爲php安裝了zmq插件,詳細情況請參考上一篇博客《環境搭建》;
<?php
/*
*  zmq-client.php
*
*  Hello World client
*  Connects REQ socket to tcp://localhost:5555
*  Sends "XXX" to C server, expects "YYY" back
* @author Ian Barber <ian(dot)barber(at)gmail(dot)com>
*/

$context = new ZMQContext();

//  Socket to talk to server
echo "<br>Connecting to hello world server…\n";
$requester = new ZMQSocket($context, ZMQ::SOCKET_REQ);
$requester->connect("tcp://localhost:5555");

for ($request_nbr = 0; $request_nbr != 10; $request_nbr++) {
    printf ("<br>Sending request %d…\n", $request_nbr);
    $requester->send("Hello from php client!");

    $reply = $requester->recv();
    printf ("<br>Received reply %d: [%s]\n", $request_nbr, $reply);
}

?>
        客戶端代碼:hello_world_server.c
           版權說明:此代碼是ZMQ官網測試代碼,可能做了一點修改;
           編譯說明:需要鏈接czmq庫,此處默認您已經安裝了zmq庫和czmq庫;
// hello_world_server.c
// Hello World server

#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

#define BUFFER_LEN 64

int main (void)
{
    //  Socket to talk to clients
    void *context = zmq_ctx_new ();
    void *responder = zmq_socket (context, ZMQ_REP);
    int rc = zmq_bind (responder, "tcp://*:5555");
    assert (rc == 0);

    while (1) {
        char buffer [BUFFER_LEN];
        zmq_recv (responder, buffer, BUFFER_LEN, 0);
        printf ("Received:[%s]\n", buffer);
        zmq_send (responder, "World from c server", strlen("World from c server"), 0);
        sleep (1);          //  Do some 'work'
    }
    return 0;
}


          
        測試結果(客戶端):

 

            測試結果(服務端):

 
helloworld示例到此演示完畢,下一篇博客將演示ZMQ的MDP模式:php-client、c-broker和c-server。
發佈了13 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章