服务端
vim rpcserver.php
<?php
$server=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($server,'127.0.0.1',9090) or die("error");
socket_listen($server,5);
while(true) {
$client=socket_accept($server);
$buf=socket_read($client,8024);
echo $buf.PHP_EOL;
if(preg_match("/GET\s\/(.*?)\sHTTP\/1.1/i",$buf,$matchs)) {
$path = $matchs[1];
echo 'path ==>'.$path.PHP_EOL;
if(file_exists($path))
{
require_once $path;
$classes=get_declared_classes();
$obj_class_name=end($classes);
$obj=new $obj_class_name();//实例化
$result="";
if(preg_match("/EXEC\s(.*?)\s/i",$buf,$matchs)) {
$methodName=$matchs[1];//获取自定义协议中的方法名
$result=$obj->$methodName();
socket_write($client,$result);
} else {
foreach(get_class_methods($obj) as $method) {
if($result!="") $result.=",";
$result.='"method":"'.$method.'"';
}
$result="{".$result."}";
socket_write($client,$result);
}
} else {
socket_write($client,"no service");
}
} else {
socket_write($client,"404");
}
socket_close($client);
}
socket_close($server);
客户端
vim rpcclient.php
<?php
$client=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_connect($client,'127.0.0.1',9090);
$http="GET /service/Test.php HTTP/1.1".PHP_EOL;
$http.="EXEC hehe ".PHP_EOL;
socket_write($client,$http);
$buf=socket_read($client,8024);
echo $buf.PHP_EOL;
调用类准备
- 在当前目录下新建service文件夹
- 在service目录下新建调用类
vim Test.php
<?php
class Test{
public function hehe() {
return 'hehe';
}
public function hehe2($params) {
return json_encode($params);
}
}
网友评论