计算机网络/计算机科学与应用/系统/运维/开发

Swoole TCP 面向对象封装

在nginx 目录下创建一个client目录 和一个TCP.php 

[root@VM-4-2-centos swoole]# pwd

/usr/local/nginx/html/myphp/swoole

[root@VM-4-2-centos swoole]# ll

total 8

drwxr-xr-x 2 root root 4096 Aug 11 16:25 client

-rw-r--r-- 1 root root  757 Aug 11 16:14 TCP.php



<?php

 class TCP{

        private $server = null;

        public function __construct(){

                $this->server = new Swoole\Server("127.0.0.1",9501);

                $this->server->set([

                        'worker_num'    => 4,     // worker process num

                        'max_request'   => 50,

                ]);

                $this->server->on('Connect',[$this,"onConnect"]);

                $this->server->on('Receive',[$this,"onRecevice"]);

                $this->server->on('Close',[$this,"onClose"]);

                $this->server->start();

        }


        public function onConnect($server,$fd){

                echo "客户端id:{$fd}链接.\n";

        }


        public function onRecevice($server,$fd,$from_id,$data){

                $server->send($fd,"发送的数据:".$data);

        }


        public function onClose($server,$fd){

                echo "客户端id:{$fd}关闭.\n";

        }

}


new TCP();



[root@VM-4-2-centos client]# pwd

/usr/local/nginx/html/myphp/swoole/client

[root@VM-4-2-centos client]# ll

total 4

-rw-r--r-- 1 root root 393 Aug 11 16:25 TCP.php


内容如下:

<?php

use Swoole\Coroutine\Client;

use function Swoole\Coroutine\run; 


run(function () {

    $client = new Client(SWOOLE_SOCK_TCP);

    if (!$client->connect('127.0.0.1', 9501, 0.5))

    {

        echo "connect failed. Error: {$client->errCode}\n";

    }

    fwrite(STDOUT,"请输入:");

    $res = fgets(STDIN);

    $client->send($res);

    echo $client->recv();

    $client->close();

});



# 执行结果

[root@VM-4-2-centos swoole]# php TCP.php 


客户端id:1链接.

客户端id:1关闭.

客户端id:2链接.

客户端id:2关闭.

客户端id:3链接.

客户端id:3关闭.



[root@VM-4-2-centos client]# php TCP.php 

请输入:1

发送的数据:1

[root@VM-4-2-centos client]# php TCP.php 

请输入:swoole

发送的数据:swoole


php swoole

努力的意义,不在于一定会让你取得多大的成就,只是让你在平凡的日子里,活得比原来的那个自己更好一点。

评论

^