企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
TCP Server ~~~ //创建Server对象,监听 127.0.0.1:9501端口 $serv = new Swoole\Server("127.0.0.1", 9501); //监听连接进入事件 $serv->on('Connect', function ($serv, $fd) { echo "Client: Connect.\n"; }); //监听数据接收事件 $serv->on('Receive', function ($serv, $fd, $from_id, $data) { $serv->send($fd, "Server: ".$data); }); //监听连接关闭事件 $serv->on('Close', function ($serv, $fd) { echo "Client: Close.\n"; }); //启动服务器 $serv->start(); ~~~ 后台CLI连接到这个服务器 ``` telnet 127.0.0.1 9501 ``` TCP Client(同步) ~~~ $client = new swoole_client(SWOOLE_SOCK_TCP); //连接到服务器 if (!$client->connect('127.0.0.1', 9501, 0.5)) { die("connect failed."); } //向服务器发送数据 if (!$client->send("hello world")) { die("send failed."); } //从服务器接收数据 $data = $client->recv(); if (!$data) { die("recv failed."); } echo $data; //关闭连接 $client->close(); ~~~ TCP Client(异步) ~~~ $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //注册连接成功回调 $client->on("connect", function($cli) { $cli->send("hello world\n"); }); //注册数据接收回调 $client->on("receive", function($cli, $data){ echo "Received: ".$data."\n"; }); //注册连接失败回调 $client->on("error", function($cli){ echo "Connect failed\n"; }); //注册连接关闭回调 $client->on("close", function($cli){ echo "Connection close\n"; }); //发起连接 $client->connect('127.0.0.1', 9501, 0.5); ~~~