Golang 服務端
package main
import (
"fmt"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)
type Goods struct{}
func (g *Goods) GetName(args string , res *string) error {
*res = "args=" + args
return nil
}
func main() {
err := rpc.RegisterName("Goods",new(Goods))
if err != nil {
panic(err.Error())
}
listen, err := net.Listen("tcp", "127.0.0.1:7081")
if err != nil {
panic(err.Error())
}
fmt.Println("啟動服務...")
for {
conn, err := listen.Accept()
if err != nil {
continue
}
go jsonrpc.ServeConn(conn)
}
}
PHP 客戶端
public function test(){
$host = '127.0.0.1';
$port = '7081';
$conn = fsockopen($host, $port, $errno, $errstr, 3);
if (!$conn) {
dd('連結失敗');
}
$method = 'Goods.GetName';
$params = "我是字串引數";
$err = fwrite($conn, json_encode(array(
'method' => $method,
'params' => [$params],
'id' => 0,
))."\n");
if ($err === false){
dd('寫入資料失敗');
}
stream_set_timeout($conn, 0, 30000);
$line = fgets($conn);
if ($line === false) {
dd('獲取響應資料失敗');
}
dd(json_decode($line,true));
}
返回結果
array:3 [
"id" => 0
"result" => "args=我是字串引數"
"error" => null
]
本作品採用《CC 協議》,轉載必須註明作者和本文連結