天天看点

Swoole---tcp(协程风格)

服务端

<?php

//多进程管理模块
$pool = new Swoole\Process\Pool(2);//开启多进程,设置两个进程工作数量,第二个参数默认为 0表示不使用任何进程间通信特性
//让每个OnWorkerStart回调都自动创建一个协程
$pool->set(['enable_coroutine' => true]);
/*
 * 当enable_coroutine设置为true时,底层自动在onRequest回调中创建协程,开发者无需自行使用go函数创建协程
   当enable_coroutine设置为false时,底层不会自动创建协程,开发者如果要使用协程,必须使用go自行创建协程,
   如果不需要使用协程特性,则处理方式与1.x是100%一致的
 * */
$pool->on("workerStart", function ($pool, $id) {
    //每个进程都监听9501端口
    $server = new Swoole\Coroutine\Server('127.0.0.1', '9501' , false, true);//第三个参数是否开启ssl加密,第四个参数是否开启端口重用
    //收到15信号关闭服务
    Swoole\Process::signal(SIGTERM, function () use ($server) {
        $server->shutdown();
    });
    //接收到新的连接请求
    $server->handle(function (Swoole\Coroutine\Server\Connection $conn) {
        //接收数据
        $data = $conn->recv();
        if (empty($data)) {
            //关闭连接
            $conn->close();
        }
        echo $data;
        //发送数据
        $conn->send("hello");
    });
    //开始监听端口
    $server->start();
});
$pool->start();

           

客户端

go(function (){
	//实例化必须放到协程里面不然报错
    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
    if (!$client->connect("127.0.0.1",9501)){
        echo  "连接失败".$client->errCode.PHP_EOL;
    }else{
        $client->send("hello\n");
        echo $client->recv();
        $client->close();
    }
});
           

执行结果

hello
//客户端和服务端都能接收到相互的数据