Use PHP to create a simple RPC service

Source: Internet
Author: User
Tags fread

RPC is all called remote Procedure call, which translates to "remoting procedure calls". It is mainly used for remote communication and mutual invocation between different systems.

For example, there are two systems, one is written by PHP, one is written in Java, and PHP wants to call a method of a class in Java, then it needs to use RPC.

What's the tune? Direct tuning is not possible, only PHP through a custom protocol to request the Java service, Java resolves the protocol, instantiate the class locally and invoke the method, and then return the results to PHP.

Here we use the PHP socket extension to create a server and client to demonstrate the invocation process.

The rpcserver.php code is as follows:

<?phpclass Rpcserver {protected $serv = null; Public function __construct ($host, $port, $path) {//Create a TCP socket service $this->serv = Stream_socket_server (        "Tcp://{$host}:{$port}", $errno, $ERRSTR);        if (! $this->serv) {exit ("{$errno}: {$errstr} \ n");        }//To determine if our RPC service directory exists $realPath = Realpath (__dir__. $path);        if ($realPath = = = False | |!file_exists ($REALPATH)) {exit ("{$path} error \ n");            } while (true) {$client = stream_socket_accept ($this->serv);                if ($client) {//Here for simplicity, we read it once $buf = Fread ($client, 2048);                Parse the protocol that the client sent over $classRet = Preg_match ('/rpc-class:\s (. *); \r\n/i ', $buf, $class);                $methodRet = Preg_match ('/rpc-method:\s (. *); \r\n/i ', $buf, $method);                                $paramsRet = Preg_match ('/rpc-params:\s (. *); \r\n/i ', $buf, $params); if ($classRet &&$methodRet) {$class = Ucfirst ($class [1]); $file = $realPath. ‘/‘ . $class.                    '. php ';                        Determine if the file exists, if any, then introduce the file if (file_exists ($file)) {require_once $file;                        Instantiate the class and invoke the method specified by the client $obj = new $class ();                        If there is an argument, pass in the specified parameter if (! $paramsRet) {$data = $obj $method [1] ();                        } else {$data = $obj $method [1] (Json_decode ($params [1], true));                    }//Return the results of the run to the client fwrite ($client, $data);                }} else {fwrite ($client, ' class or method error ');            }//Close client fclose ($client);    }}} Public function __destruct () {fclose ($this->serv); }}new rpcserver (' 127.0.0.1 ', 8888, './service '); 

The

rpcclient.php code is as follows:

<?phpclass rpcclient {protected $urlInfo = array ();        Public function __construct ($url) {//parse URL $this->urlinfo = Parse_url ($url);        if (! $this->urlinfo) {exit ("{$url} error \ n"); }} Public Function __call ($method, $params) {//Create a client $client = Stream_socket_client ("tcp://{$t        his->urlinfo[' host ']}:{$this->urlinfo[' Port '} ", $errno, $ERRSTR);        if (! $client) {exit ("{$errno}: {$errstr} \ n");        }//The class name of the pass call $class = basename ($this->urlinfo[' path '); $proto = "Rpc-class: {$class};".        Php_eol; The method name of the delivery call $proto. = "Rpc-method: {$method};".        Php_eol;        The parameter of the delivery method $params = Json_encode ($params); $proto. = "Rpc-params: {$params};".        Php_eol;        Send our custom protocol data to the server fwrite ($client, $proto);        Read data from the server $data = Fread ($client, 2048);        Close client fclose ($client);    return $data; }} $cli = new RpCclient (' http://127.0.0.1:8888/test '); Echo $cli->hehe (); Echo $cli->hehe2 (Array (' name ' = ' Test ', ' age ' = > 27));

Then run the above two scripts separately (note that PHP will add environment variables)

> PHP rpcserver.php> php rpcclient.php

The results are as follows:

The test.php code is as follows:

<?phpclass Test {public    function hehe () {        return ' hehe ';    }    Public Function Hehe2 ($params) {        return Json_encode ($params);}    }

The directory structure is as follows:

Above our custom protocol, can be arbitrarily modified, as long as the client and the server side can be unified and can be resolved.

The client passes the class, methods and parameters to be called to the server by requesting the service side, and the server returns the result by instantiating the calling method.

Use PHP to create a simple RPC service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.