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

Swoole UDP面向对象封装

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

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

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

total 12

drwxr-xr-x 2 root root 4096 Aug 11 17:30 client

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

-rw-r--r-- 1 root root  587 Aug 11 17:36 UDP.php


UDP.php 


<?php

 class UDP{

        private $server = null;

        public function __construct(){

                $this->server = new Swoole\Server('127.0.0.1', 9502, SWOOLE_PROCESS, SWOOLE_SOCK_UDP);



                $this->server->set([

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

                        'max_request'   => 50,

                ]);


                $this->server->on('Packet',[$this,"onPacket"]);

                $this->server->start();

        }




        public function onPacket($server,$data, $clientInfo){

                 $server->sendto($clientInfo['address'], $clientInfo['port'], "Server:{$data}");

                 var_dump($clientInfo);

        }

}


new UDP();


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


array(5) {

  ["server_socket"]=>

  int(3)

  ["dispatch_time"]=>

  float(1660210482.6864)

  ["server_port"]=>

  int(9502)

  ["address"]=>

  string(9) "127.0.0.1"

  ["port"]=>

  int(33152)

}




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

total 8

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

-rw-r--r-- 1 root root 393 Aug 11 17:30 UDP.php

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

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



<?php

use Swoole\Coroutine\Client;

use function Swoole\Coroutine\run;


run(function () {

    $client = new Client(SWOOLE_SOCK_UDP);

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

    {

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

    }

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

    $res = fgets(STDIN);

    $client->send($res);

    echo $client->recv();

    $client->close();

});


swoole php

人生活在得失之间,得亦是失,失亦是得。

评论

^