Swoole simply implements the RPC principle

What is RPC

The full name of RPC is Remote Procedure Call, which is translated into remote procedure call in Chinese. In fact, you can understand it as an architectural design or a solution.
Through RPC, we can call methods on other machines just like calling local methods, and users will not be aware of the communication between the server and the server. RPC plays a considerable role in microservices.

Common operations

View the process id under the current port 8887 in order to kill the process

netstat -nap |grep 8887

Insert picture description here

Enable swoole's server service without occupying the panel

nohup php swoole_server.php user >/dev/null 2>&1 &

swoole_server.php

<?php
//创建tcp服务
$serv = new swoole_server('127.0.0.1', 8887);
$serv->set(array('worker_num' => 2));
$serv->on("receive", function ($serv, $fd, $from_id, $data) {
    
    
    //$data 接受客户端发送的数据
    $data = json_decode($data, true);
    $site = $data['site'];
    $action = $data['action'];
    $result['site'] = $site;
    print_r($result);
    $result['action'] = $action;
    //给客户端发送数据
    $serv->send($fd, json_encode(['data' => $result]));
});
$serv->start();

swoole_client.php

<?php
//客户端:
$cli = new swoole_client(SWOOLE_SOCK_TCP);
$cli->connect('127.0.0.1', 8887);
$data=json_encode(['site'=>'user','action'=>'index']);
$cli->send($data);
$result=$cli->recv();//接收消息
$cli->close();
var_dump($result);

Results page

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_39218464/article/details/113784897