phprpc 使用实例(同时有Java、Android和Delphi客户端的例子)

时间:2023-03-09 19:47:25
phprpc 使用实例(同时有Java、Android和Delphi客户端的例子)

PHPRPC 是一个轻型的、安全的、跨网际的、跨语言的、跨平台的、跨环境的、跨域的、支持复杂对象传输的、支持引用参数传递的、支持内容输出重定向的、支持分级错误处理的、支持会话的、面向服务的高性能远程过程调用协议。

遇到的问题总结:

Fatal error: Cannot redeclare gzdecode() in
1、重命名compat.php、phprpc_client.php的gzdecode(和系统函数冲突)函数为gzdecode_other

Non-static method PHPRPC_Server::initSession() should not be called statically
 2、修改phprpc_server.php文件里面initSession函数的类型为static即可。

3、phprpc_client.php 472行警告:
Notice: Undefined offset in phprpc_client.php line 472
修改成
 $arr = explode('=', $c, 2);
                    if(count($arr)>1)
                    {
                        list($name, $value)=$arr;
                        if (!in_array($name, array('domain', 'expires', 'path', 'secure'))) {
                            $_PHPRPC_COOKIES[$name] = $value;
                        }
                    }
4、Warning: The magic method __get() must have public visibility and cannot be static in compat.php(235) : eval()'d code on line 3
改成public:
eval('
    class ' . $classname . ' {
        public function __get($name) {

php server端

  1. <?php
  2. include ('php/phprpc_server.php');
  3. include 'entitys.php';
  4. function hello($name)
  5. {
  6. return 'Hello ' . $name;
  7. }
  8. $server = new PHPRPC_Server();
  9. $server->setCharset('UTF-8');
  10. $server->setDebugMode(true);
  11. $server->setEnableGZIP(true);
  12. $server->add('hello');
  13. $server->add('sort');
  14. //$server->add(array('hello','md5','sha1'));
  15. $server->add('getcwd');//导出php内置函数
  16. $server->add('add', new Calculator());
  17. $server->add('mul', new Calculator());
  18. $server->add('div', new Calculator());
  19. $server->add('sub', new Calculator());
  20. $server->add('fuck', new Calculator());
  21. $server->add('getstudent', new Calculator());
  22. $server->add('getstudents', new Calculator());
  23. $server->start();
  24. ?>
  1. <?php
  2. class Student
  3. {
  4. public $id;
  5. public $name;
  6. public $age;
  7. }
  8. /**
  9. * Calculator - sample class to expose via JSON-RPC
  10. */
  11. class Calculator
  12. {
  13. /**
  14. * Return sum of two variables
  15. *
  16. * @param int $x
  17. * @param int $y
  18. * @return int
  19. */
  20. public function add($x, $y)
  21. {
  22. return $x + $y;
  23. }
  24. /**
  25. * Return difference of two variables
  26. *
  27. * @param int $x
  28. * @param int $y
  29. * @return int
  30. */
  31. public function sub($x, $y)
  32. {
  33. return $x - $y;
  34. }
  35. /**
  36. * Return product of two variables
  37. *
  38. * @param int $x
  39. * @param int $y
  40. * @return int
  41. */
  42. public function mul($x, $y)
  43. {
  44. return $x * $y;
  45. }
  46. /**
  47. * Return the division of two variables
  48. *
  49. * @param int $x
  50. * @param int $y
  51. * @return float
  52. */
  53. public function div($x, $y)
  54. {
  55. return $x / $y;
  56. }
  57. public function fuck($str, $x, $y)
  58. {
  59. $m = $x + $y;
  60. return 'fuck 日本' . $str . $m;
  61. }
  62. public function getstudent($student)
  63. {
  64. $student = new Student();
  65. $student->id = 110;
  66. $student->name = 'php';
  67. $student->age = 21;
  68. return $student;
  69. }
  70. public function getstudents($id)
  71. {
  72. $entitys = array();
  73. for ($i=0;$i<10;$i++) {
  74. $student = new Student();
  75. $student->id = $i;
  76. $student->name = '中文php'.$i;
  77. $student->age = 21;
  78. array_push($entitys, $student);
  79. }
  80. return $entitys;
  81. }
  82. }
  83. ?>

php client客户端

  1. <?php
  2. include ("php/phprpc_client.php");
  3. $client = new PHPRPC_Client('http://localhost/phprpc/index.php');
  4. echo '<br/>';
  5. $ret=$client->add(12,32);
  6. print_r($ret);
  7. echo '<br/>';
  8. $ret=$client->mul(12,32);
  9. print_r($ret);
  10. echo '<br/>';
  11. $ret=$client->fuck('xx测试',12,32);
  12. print_r($ret);
  13. echo '<br/>';
  14. $ret=$client->hello('xx测试',12,32);
  15. print_r($ret);
  16. echo '<br/>';
  17. $ret=$client->getstudent('getstudent');
  18. print_r($ret);
  19. echo '<br/>';
  20. $ret=$client->getstudents('getstudents');
  21. print_r($ret);
  22. echo '<br/>';
  23. print_r($client->getOutput());
  24. ?>

java  客户端:

  1. package com.jiepu.client;
  2. import org.phprpc.PHPRPC_Client;
  3. import org.phprpc.util.AssocArray;
  4. import org.phprpc.util.Cast;
  5. public class IncClient {
  6. // http://leyteris.iteye.com/blog/1004669
  7. //http://www.phprpc.org/zh_CN/docs/
  8. //android下面也一样
  9. public static void main(String[] args) {
  10. PHPRPC_Client client = new PHPRPC_Client(
  11. "http://10.0.0.108/phprpc/index.php");
  12. System.out.println(client.invoke("add", new Object[] { 12, 32 }));
  13. System.out.println(client.invoke("sub", new Object[] { 12, 32 }));
  14. System.out.println(client.invoke("mul", new Object[] { 12, 32 }));
  15. System.out.println(client.invoke("div", new Object[] { 12, 32 }));
  16. System.out.println(Cast.toString(client.invoke("fuck", new Object[] {
  17. "hehe你好", 12, 32 })));
  18. System.out.println(Cast.toString(client.invoke("getcwd", new Object[] {})));
  19. System.out.println(Cast.toString(client.invoke("hello",
  20. new Object[] { "java" })));
  21. //public公共类Student自动映射转换
  22. Object obj=client.invoke("getstudent",new Object[] { "java" });
  23. Student stu=(Student) Cast.cast(obj, Student.class);
  24. System.out.println(stu);
  25. /**手动转换
  26. HashMap<Object, Object> objs = (HashMap<Object, Object>) client.invoke("getstudent",
  27. new Object[] { "java" });
  28. if(objs.size()>0)
  29. {
  30. Student student = new Student();
  31. student.setAge(Integer.parseInt(Cast.toString(objs.get("age"))));
  32. student.setName(Cast.toString(objs.get("name")));
  33. student.setId(Integer.parseInt(Cast.toString(objs.get("id"))));
  34. System.out.println(student);
  35. System.out.println("===========");
  36. }*/
  37. AssocArray alist = (AssocArray) client.invoke("getstudents",
  38. new Object[] { "java" });
  39. for (int i = 0; i < alist.size(); ++i) {
  40. // System.out.println(alist.get(i).getClass());
  41. Student student=(Student) Cast.cast(alist.get(i), Student.class);
  42. System.out.println(student);
  43. }
  44. // System.out.println(client.getWarning());
  45. }
  46. }
  1. package com.jiepu.client;
  2. import java.io.Serializable;
  3. public class Student implements Serializable {
  4. private static final long serialVersionUID = 3475272786622279878L;
  5. private Integer id;
  6. private String name;
  7. private Integer age;
  8. @Override
  9. public String toString() {
  10. return "Student [age=" + age + ", id=" + id + ", name=" + name
  11. + "]";
  12. }
  13. public Integer getId() {
  14. return id;
  15. }
  16. public void setId(Integer id) {
  17. this.id = id;
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. public Integer getAge() {
  26. return age;
  27. }
  28. public void setAge(Integer age) {
  29. this.age = age;
  30. }
  31. }

android客户端:

  1. package com.example.androidjsonrpc;
  2. import java.util.List;
  3. import org.alexd.jsonrpc.JSONRPCClient;
  4. import org.alexd.jsonrpc.JSONRPCException;
  5. import org.alexd.jsonrpc.JSONRPCParams.Versions;
  6. import org.phprpc.PHPRPC_Client;
  7. import org.phprpc.util.AssocArray;
  8. import org.phprpc.util.Cast;
  9. import android.app.Activity;
  10. import android.os.Bundle;
  11. import android.util.Log;
  12. import android.view.View;
  13. import com.alibaba.fastjson.JSON;
  14. public class MainActivity extends Activity {
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. }
  20. public void run(View view) {
  21. new Thread(new Runnable() {
  22. @Override
  23. public void run() {
  24. runinthread();
  25. }
  26. }).start();
  27. }
  28. public void runphprpc(View view) {
  29. new Thread(new Runnable() {
  30. @Override
  31. public void run() {
  32. runphprpc();
  33. }
  34. }).start();
  35. }
  36. private void runphprpc() {
  37. PHPRPC_Client client = new PHPRPC_Client(
  38. "http://10.0.0.108/phprpc/index.php");
  39. System.out.println(client.invoke("add", new Object[] { 12, 32 }));
  40. System.out.println(client.invoke("sub", new Object[] { 12, 32 }));
  41. System.out.println(client.invoke("mul", new Object[] { 12, 32 }));
  42. System.out.println(client.invoke("div", new Object[] { 12, 32 }));
  43. System.out.println(Cast.toString(client.invoke("fuck", new Object[] {
  44. "hehe你好", 12, 32 })));
  45. System.out.println(Cast.toString(client.invoke("getcwd", new Object[] {})));
  46. System.out.println(Cast.toString(client.invoke("hello",
  47. new Object[] { "java" })));
  48. //public公共类Student自动映射转换
  49. Object obj=client.invoke("getstudent",new Object[] { "java" });
  50. Student stu=(Student) Cast.cast(obj, Student.class);
  51. System.out.println(stu);
  52. /**手动转换
  53. HashMap<Object, Object> objs = (HashMap<Object, Object>) client.invoke("getstudent",
  54. new Object[] { "java" });
  55. if(objs.size()>0)
  56. {
  57. Student student = new Student();
  58. student.setAge(Integer.parseInt(Cast.toString(objs.get("age"))));
  59. student.setName(Cast.toString(objs.get("name")));
  60. student.setId(Integer.parseInt(Cast.toString(objs.get("id"))));
  61. System.out.println(student);
  62. System.out.println("===========");
  63. }*/
  64. AssocArray alist = (AssocArray) client.invoke("getstudents",
  65. new Object[] { "java" });
  66. for (int i = 0; i < alist.size(); ++i) {
  67. // System.out.println(alist.get(i).getClass());
  68. Student student=(Student) Cast.cast(alist.get(i), Student.class);
  69. System.out.println(student);
  70. }
  71. }
  72. public void runinthread() {
  73. // https://code.google.com/p/android-json-rpc/downloads/list
  74. // http://www.oschina.net/p/android-json-rpc
  75. JSONRPCClient client = JSONRPCClient.create(
  76. "http://10.0.0.107/json_server/server.php", Versions.VERSION_2);
  77. client.setConnectionTimeout(2000);
  78. client.setSoTimeout(2000);
  79. try {
  80. String string = client.callString("fuck", "android谷歌", 15, 32);
  81. Log.i("androidjsonrpc", "fuck=" + string);
  82. int i = client.callInt("add", 56, 25);
  83. Log.i("androidjsonrpc", i + "");
  84. // Student student=(Student) client.call("getstudent", new
  85. // Student(1,"name",123));
  86. // Log.i("androidjsonrpc", student.toString());
  87. // Log.i("androidjsonrpc", client.call("getstudent", new
  88. // Student(1,"name",123)).toString());
  89. // Log.i("androidjsonrpc", client.call("getstudents",
  90. // "xx").toString());
  91. String str = client.callString("getstudent", new Student(1, "name",
  92. 123));
  93. Log.i("androidjsonrpc", str);
  94. // fastjson 转换json字符串为对象
  95. Student student = JSON.parseObject(str, Student.class);
  96. Log.i("androidjsonrpc", student.toString());
  97. str = client.callString("getstudents", "xx");
  98. Log.i("androidjsonrpc", str);
  99. // 使用到fastjson 转换json数组为list对象
  100. List<Student> students = JSON.parseArray(str, Student.class);
  101. Log.i("androidjsonrpc", students.toString());
  102. } catch (JSONRPCException e) {
  103. e.printStackTrace();
  104. }
  105. }
  106. }

Delphi 客户端:

  1. unit Unit4;
  2. interface
  3. uses
  4. Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  5. Dialogs, PHPRPCSynaHttpClient, PHPRPC, PHPRPCClient, PHPRPCIdHttpClient,
  6. StdCtrls;
  7. type
  8. TForm4 = class(TForm)
  9. Button1: TButton;
  10. PHPRPCIdHttpClient1: TPHPRPCIdHttpClient;
  11. PHPRPCSynaHttpClient1: TPHPRPCSynaHttpClient;
  12. procedure Button1Click(Sender: TObject);
  13. private
  14. { Private declarations }
  15. public
  16. { Public declarations }
  17. end;
  18. TStudent = class(TPHPObject)
  19. private
  20. Fid: Integer;
  21. Fname: AnsiString;
  22. Fage: Integer;
  23. published
  24. property id: Integer read Fid write Fid;
  25. property name: AnsiString read Fname write Fname;
  26. property age: Integer read Fage write Fage;
  27. end;
  28. var
  29. Form4: TForm4;
  30. implementation
  31. {$R *.dfm}
  32. procedure TForm4.Button1Click(Sender: TObject);
  33. var
  34. clientProxy: Variant;
  35. int_ret, i: Integer;
  36. string_ret: string;
  37. vhashmap: Variant;
  38. ohashmap: THashMap;
  39. arraylist, keys, values: TArrayList;
  40. key, value, tmp: Variant;
  41. student: TStudent;
  42. begin
  43. // http://www.phprpc.org/zh_CN/docs/
  44. clientProxy := PHPRPCIdHttpClient1.useService
  45. ('http://10.0.0.108/phprpc/index.php');
  46. int_ret := clientProxy.add(12, 52);
  47. ShowMessage(IntToStr(int_ret));
  48. // 中文字符串参数要转换为UTF8编码
  49. string_ret := clientProxy.fuck(AnsiToUTF8('xxx你好'), 15, 45);
  50. // 中文的服务器输出的也是UTF8编码,本地打印要转换为本地编码
  51. ShowMessage(UTF8ToAnsi(string_ret));
  52. string_ret := clientProxy.getcwd();
  53. ShowMessage(UTF8ToAnsi(string_ret));
  54. string_ret := clientProxy.hello(AnsiToUTF8('xxx'));
  55. ShowMessage(UTF8ToAnsi(string_ret));
  56. TStudent.RegisterClass('Student');
  57. tmp := clientProxy.getstudent(AnsiToUTF8('java'));
  58. // ShowMessage(UTF8ToAnsi(tmp));
  59. // 转换为student对象
  60. student := TStudent(TStudent.FromVariant(tmp));
  61. ShowMessage(IntToStr(student.id) + ',' + UTF8ToAnsi(student.name)+ ',' + IntToStr
  62. (student.age));
  63. vhashmap := clientProxy.getstudents(AnsiToUTF8('java'));
  64. ohashmap := THashMap(THashMap.FromVariant(vhashmap));
  65. arraylist := ohashmap.ToArrayList;
  66. for i := 0 to arraylist.Count - 1 do
  67. begin
  68. // ShowMessage(arraylist.Items[i]);
  69. student := TStudent(TStudent.FromVariant(arraylist.Items[i]));
  70. ShowMessage(IntToStr(student.id) + ',' + UTF8ToAnsi(student.name)+ ',' + IntToStr
  71. (student.age));
  72. end;
  73. arraylist.Free;
  74. { keys:=ohashmap.Keys;
  75. values:=ohashmap.Values;
  76. for i := 0 to keys.Count - 1 do
  77. begin
  78. key:=keys[i];
  79. value:=values[i];
  80. ShowMessage(values.List[i]);
  81. ShowMessage(value);
  82. // ohashmap := THashMap(THashMap.FromVariant(value));
  83. //ShowMessage(ohashmap.Values[0].Properties['name']);
  84. end;
  85. }
  86. end;
  87. end.

源码下载:http://pan.baidu.com/s/1eQ6KOcq

http://blog.csdn.net/earbao/article/details/46428565