How to IPC between PHP clients and a C Daemon Server?

后端 未结 7 1095
春和景丽
春和景丽 2020-12-02 13:32

and thanks for taking a look at the question.

The background
I have several machines that continuously spawn multiple (up to 300) PHP console sc

7条回答
  •  青春惊慌失措
    2020-12-02 14:00

    nanomsg is coded in plain C so I guess it is better suited for your needs than Thrift and ZeroMQ that are coded in C++.

    It has wrappers for many languages including PHP.

    Here is a working example using the NN_PAIR protocol: (you can use NN_REQREP too)

    client.php

    connect('ipc:///tmp/myserver.ipc');
    
    $sock->send('Hello World!', 0);
    
    $sock->setOption(NanoMsg::NN_SOL_SOCKET, NanoMsg::NN_RCVTIMEO, 1000);
    
    $data = $sock->recv(0, 0);
    
    echo "received: " . $data . "\n";
    
    ?>
    

    server.c

    #include 
    #include 
    #include 
    #include 
    
    #define address "ipc:///tmp/myserver.ipc"
    
    int main() {
      unsigned char *buf = NULL;
      int result;
      int sock = nn_socket(AF_SP, NN_PAIR);
      if (sock < 0) puts("nn_socket failed");
    
      if (nn_bind(sock, address) < 0) puts("bind failed");
    
      while ((result = nn_recv(sock, &buf, NN_MSG, 0)) > 0) {
        int i, size = strlen(buf) + 1;  // includes null terminator
        printf("RECEIVED \"%s\"\n", buf);
        for (i = 0; buf[i] != 0; i++)
          buf[i] = toupper(buf[i]);
        nn_send(sock, buf, size, 0);
        nn_freemsg(buf);
      }
      nn_shutdown(sock, 0);
      return result;
    }
    

提交回复
热议问题