一、swoole的安装
参照官网:https://wiki.swoole.com/wiki/page/6.html
二、代码部分
服务端:
<?php $host = "127.0.0.1"; $port = 9501; $mode = SWOOLE_PROCESS; // 多进程模式 默认 $sock_type = SWOOLE_SOCK_TCP; // 创建tcp socket 默认 //创建Server对象,监听 127.0.0.1:9501端口 $serv = new swoole_server($host, $port, $mode, $sock_type); $serv->set([ // ps aft | grep php 查看 'worker_num' => 4, // worker进程数 cpu核数的1-4倍 'max_request' => 10000, ]); //监听连接进入事件 /** * $fd 客户端连接的唯一标识符 * $reactor_id 线程id */ $serv->on('connect', function ($serv, $fd, $reactor_id) { echo "Client: {$fd} - {$reactor_id} - Connect. "; }); //监听数据接收事件 $serv->on('receive', function ($serv, $fd, $reactor_id, $data) { $serv->send($fd, "Server: {$fd} - {$reactor_id} - ".$data); }); //监听连接关闭事件 $serv->on('close', function ($serv, $fd) { echo "Client: {$fd} - Close. "; }); //启动服务器 $serv->start();
客户端:
<?php // 连接 tcp server服务器 $client = new swoole_client(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 9501)) { exit("connect failed. Error: {$client->errCode} "); } // php cli常量 fwrite(STDIN, "请输入消息:"); $msg = trim(fgets(STDOUT)); // 发送消息get tcp server 服务器 $client->send("{$msg} "); // 接收来自server的数据 echo $result = $client->recv(); $client->close();
也可通过 命令行:
# telnet 127.0.0.1 9501
进行测试