Swoole Posted on 2021-06-04 TCP面向对象1234567891011121314151617181920212223242526272829303132333435363738394041424344<?php//服务端class TCP{ private $server = null; public function __construct() { //创建Server对象,监听 127.0.0.1:9501 端口 $this->server = new Swoole\Server('127.0.0.1', 9501); $this->server->set([ 'worker_num' => 4, 'max_request' => 50, ]); $this->server->on('Connect', [$this, "onConnect"]); $this->server->on('Receive', [$this, "onReceive"]); $this->server->on('Close', [$this, "onClose"]); $this->server->start(); } //监听连接进入事件 public function onConnect($server, $fd) { echo "客户端id:" . $fd . "连接.\n"; } //监听数据接收事件 public function onReceive($server, $fd, $reactor_id, $data) { $server->send($fd, "发送的数据: {$data}"); } //监听连接关闭事件 public function onClose($server, $fd){ echo "客户端id:" . $fd . "关闭.\n"; }}new TCP();?> 123456789101112131415161718<?php//客服端use Swoole\Coroutine\Client;use function Swoole\Coroutine\run;go(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."\n"); echo $client->recv(); $client->close();});?>