三、快速起步

3.1、进程管理

PHP-swoole快速起步_服务器
swoole是一个多进程,多线程的服务
master主进程负责创建多个线程来接受和返回用户请求,同时生成一个manager进程,manager进程负责生成和管理N多个worker和task进程,worker和task进程是负责干活的

3.2、环境准备

使用ftp或sftp上传源代码,使用phpstorm提供ftp来直接保存即上传代码。
配置phpstorm支持ftp上传
PHP-swoole快速起步_数据_02
PHP-swoole快速起步_服务器_03
PHP-swoole快速起步_客户端_04.PHP-swoole快速起步_服务器_05
设置保存就上传
PHP-swoole快速起步_数据_06
PHP-swoole快速起步_数据_07
让phpstorm更好的支持swoole开发
下载:https:///wudi/swoole-ide-helper
放到项目根目录下面就可以了
PHP-swoole快速起步_上传_08

3.3、创建TCP服务器

  • 构建Server对象
$serv = new Swoole\Server('0.0.0.0', 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
// 参数说明
$host参数用来指定监听的ip地址  0.0.0.0监听全部地址
$port监听的端口,如9501  0-1024之间,是系统默认保留的,所在建议从5000
$mode运行的模式 SWOOLE_PROCESS多进程模式(默认)  SWOOLE_BASE基本模式
$sock_type指定Socket的类型  支持TCP、UDP等
  • 设置运行时参数
$serv->set(array(
    'worker_num' => 2
));
// 参数说明
worker_num  设置启动的Worker进程数   CPU核数的1-4倍最合理
  • 注册事件回调函数
// 有新的连接进入时,在worker进程中回调
$serv->on('Connect', function(swoole_server $server, int $fd, int $reactorId){});
// 接收到数据时回调此函数,发生在worker进程中  它不能少
$serv->on('Receive', function(swoole_server $server, int $fd, int $reactor_id, string $data){});
// TCP客户端连接关闭后,在worker进程中回调此函数
$serv->on('Close', function(swoole_server $server, int $fd, int $reactorId){});
// 参数说明
$server 是swoole_server对象  $serv->connections; //当前服务器的客户端连接,可使用foreach遍历所有连接
$fd 是连接的文件描述符
$reactorId 来自那个reactor线程
$data,收到的数据内容
  • 启动服务
$serv->start();

PHP-swoole快速起步_服务器_09
测试使用telnet来进行测试

# 默认系统是没有安装telnet
yum install -y telnet

windows下,默认也是没有安装的
PHP-swoole快速起步_上传_10
PHP-swoole快速起步_客户端_11
PHP-swoole快速起步_客户端_12
使用
PHP-swoole快速起步_php_13
回车进入,按下ctrl+]再次回车,就可以发内容,退出,按ctrl+] 输入 quit 退出

3.4、tcp客户端

// 同步客户端连接
$client = new \Swoole\Client(SWOOLE_SOCK_TCP);
// 连接到服务器  ip  端口  超时时间
if (!$client->connect('127.0.0.1', 9501, 0.5))
{
    die("connect failed.");
}
// 向服务器发送数据
if (!$client->send("hello world"))
{
    die("send failed.");
}
//从服务器接收数据
$data = $client->recv();
if (!$data)
{
    die("recv failed.");
}
echo $data;
//关闭连接
$client->close();

PHP-swoole快速起步_数据_14
原生PHP实现了tcp客户端
PHP-swoole快速起步_php_15

3.5、rpc

rpc服务端
PHP-swoole快速起步_上传_16
客户端调用
PHP-swoole快速起步_服务器_17
效果
PHP-swoole快速起步_数据_18
集合到tp框架中
定义服务,引入tp入口文件
PHP-swoole快速起步_php_19
客户端调用
PHP-swoole快速起步_客户端_20
效果
PHP-swoole快速起步_上传_21