1. 新建 tcp.php
<?php //创建Server对象,监听 127.0.0.1:9501 端口 $server = new Swoole\Server('127.0.0.1', 9501); $server->set([ 'worker_num'=>4, //worker进程数 cpu 1-4 'max_request'=>10000,// ]); //监听连接进入事件i /** * $fd 客户端连接的唯一标识 * $reactor_id 线程id */ $server->on('Connect', function ($server, $fd, $reactor_id) { echo "Client:{$reactor_id} -- {$fd} -- Connect.\n"; }); //监听数据接收事件 $server->on('Receive', function ($server, $fd, $reactor_id, $data) { $server->send($fd, "Server: {$reactor_id} -- {$fd} {$data}"); }); //监听连接关闭事件 $server->on('Close', function ($server, $fd) { echo "Client: Close.\n"; }); //启动服务器 $server->start();
2.新建tcp_client.php
<?php // 连接 swoole tcp 服务 $client = new swoole_client(SWOOLE_SOCK_TCP); if(!$client->connect("127.0.0.1", 9501)) { exit("连接失败"); } //php cli 常量 fwrite(STDOUT, "请输入信息:"); $msg = trim(fgets(STDIN)); //发送消息给 tcp服务器 $client->send($msg); //接收来自 server 的数据 $result = $client->recv(); echo $result.PHP_EOL;
分别cli 模式下,启动 tcp服务,和 tcp 客户端程序。
查看tcp服务启动了几个进程
[root@kafka1 swoole]# ps aft | grep tcp.php 13365 pts/0 S+ 0:00 \_ grep --color=auto tcp.php 13112 pts/1 Sl+ 0:00 \_ php tcp.php 13113 pts/1 S+ 0:00 \_ php tcp.php 13117 pts/1 S+ 0:00 \_ php tcp.php 13118 pts/1 S+ 0:00 \_ php tcp.php 13119 pts/1 S+ 0:00 \_ php tcp.php 13120 pts/1 S+ 0:00 \_ php tcp.php
本文为崔凯原创文章,转载无需和我联系,但请注明来自冷暖自知一抹茶ckhttp://www.cksite.cn