1:先创建服务端文件
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, "max_request" => 50, ]); $this -> server -> on('Connect', [$this, "onConnect"]); $this -> server -> on('Receive', [$this, "onReceive"]); $this -> server -> on('Close', [$this, "onClose"]); $this -> server -> start(); } /** * $fd 客户端链进来的id:0/开始增长 * */ 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();
2:创建客户端文件 TCP.php
<?php // use Swoole\Coroutine\Client; // use function Swoole\Coroutine\run; go(function () { $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 9501, 0.5)) { echo "connect failed. Error: {$client->errCode}\n"; } // fwrite(STDOUT,"请输入:"); // $res = fgetc(STDIN); // $client->send($res); $client->send("你好!"); echo $client->recv(); $client->close(); });
3:打开两个终端执行服务端文件跟客户端文件php TCP.php 回车,就建立成功了