swoole 测试 发表于 2018-03-25 安装PHP安装sowoole 扩展123456789101112131415➜ package cd swoole➜ swoole git:(master) phpizeConfiguring for:PHP Api Version: 20170718Zend Module Api No: 20170718Zend Extension Api No: 320170718➜ swoole git:(master) ./configure➜ swoole git:(master) make && make installs···Build complete.Don't forget to run 'make test'.Installing shared extensions: /usr/local/Cellar/php@7.2/7.2.16/pecl/20170718/Installing header files: /usr/local/Cellar/php@7.2/7.2.16/include/php/ ws_server123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197<?phpclass Ws { CONST HOST = "0.0.0.0"; CONST PORT = 8811; CONST CHART_PORT = 8812; public $ws = null; public function __construct() { // 获取 key 有值 del $this->ws = new swoole_websocket_server(self::HOST, self::PORT); $this->ws->listen(self::HOST, self::CHART_PORT, SWOOLE_SOCK_TCP); $this->ws->set( [ 'enable_static_handler' => true, 'document_root' => "/home/work/hdtocs/swoole_mooc/thinkphp/public/static", 'worker_num' => 4, 'task_worker_num' => 4, ] ); $this->ws->on("start", [$this, 'onStart']); $this->ws->on("open", [$this, 'onOpen']); $this->ws->on("message", [$this, 'onMessage']); $this->ws->on("workerstart", [$this, 'onWorkerStart']); $this->ws->on("request", [$this, 'onRequest']); $this->ws->on("task", [$this, 'onTask']); $this->ws->on("finish", [$this, 'onFinish']); $this->ws->on("close", [$this, 'onClose']); $this->ws->start(); } /** * @param $server */ public function onStart($server) { swoole_set_process_name("live_master"); } /** * @param $server * @param $worker_id */ public function onWorkerStart($server, $worker_id) { // 定义应用目录 define('APP_PATH', __DIR__ . '/../../../application/'); // 加载框架里面的文件 //require __DIR__ . '/../thinkphp/base.php'; require __DIR__ . '/../../../thinkphp/start.php'; } /** * request回调 * @param $request * @param $response */ public function onRequest($request, $response) { if($request->server['request_uri'] == '/favicon.ico') { $response->status(404); $response->end(); return ; } $_SERVER = []; if(isset($request->server)) { foreach($request->server as $k => $v) { $_SERVER[strtoupper($k)] = $v; } } if(isset($request->header)) { foreach($request->header as $k => $v) { $_SERVER[strtoupper($k)] = $v; } } $_GET = []; if(isset($request->get)) { foreach($request->get as $k => $v) { $_GET[$k] = $v; } } $_FILES = []; if(isset($request->files)) { foreach($request->files as $k => $v) { $_FILES[$k] = $v; } } $_POST = []; if(isset($request->post)) { foreach($request->post as $k => $v) { $_POST[$k] = $v; } } $this->writeLog(); $_POST['http_server'] = $this->ws; ob_start(); // 执行应用并响应 try { think\Container::get('app', [APP_PATH]) ->run() ->send(); }catch (\Exception $e) { // todo } $res = ob_get_contents(); ob_end_clean(); $response->end($res); } /** * @param $serv * @param $taskId * @param $workerId * @param $data */ public function onTask($serv, $taskId, $workerId, $data) { // 分发 task 任务机制,让不同的任务 走不同的逻辑 $obj = new app\common\lib\task\Task; $method = $data['method']; $flag = $obj->$method($data['data'], $serv); /*$obj = new app\common\lib\ali\Sms(); try { $response = $obj::sendSms($data['phone'], $data['code']); }catch (\Exception $e) { // todo echo $e->getMessage(); }*/ return $flag; // 告诉worker } /** * @param $serv * @param $taskId * @param $data */ public function onFinish($serv, $taskId, $data) { echo "taskId:{$taskId}\n"; echo "finish-data-sucess:{$data}\n"; } /** * 监听ws连接事件 * @param $ws * @param $request */ public function onOpen($ws, $request) { // fd redis [1] \app\common\lib\redis\Predis::getInstance()->sAdd(config('redis.live_game_key'), $request->fd); var_dump($request->fd); } /** * 监听ws消息事件 * @param $ws * @param $frame */ public function onMessage($ws, $frame) { echo "ser-push-message:{$frame->data}\n"; $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s")); } /** * close * @param $ws * @param $fd */ public function onClose($ws, $fd) { // fd del \app\common\lib\redis\Predis::getInstance()->sRem(config('redis.live_game_key'), $fd); echo "clientid:{$fd}\n"; } /** * 记录日志 */ public function writeLog() { $datas = array_merge(['date' => date("Ymd H:i:s")],$_GET, $_POST, $_SERVER); $logs = ""; foreach($datas as $key => $value) { $logs .= $key . ":" . $value . " "; } swoole_async_writefile(APP_PATH.'../runtime/log/'.date("Ym")."/".date("d")."_access.log", $logs.PHP_EOL, function($filename){ // todo }, FILE_APPEND); }}new Ws(); ws_client12345678910111213141516171819202122232425262728293031323334353637<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title></head><body><h1>singwa-swoole-ws测试<h1> <script> var wsUrl = "ws://swoole.demo.com:8812"; var websocket = new WebSocket(wsUrl); //实例对象的onopen属性 websocket.onopen = function(evt) { websocket.send("hello-sinwa"); console.log("conected-swoole-success"); } // 实例化 onmessage websocket.onmessage = function(evt) { console.log("ws-server-return-data:" + evt.data); } //onclose websocket.onclose = function(evt) { console.log("close"); } //onerror websocket.onerror = function(evt, e) { console.log("error:" + evt.data); } </script></body></html> 定时器1234567891011121314151617181920212223<?phpclass Server { const PORT = 8811; public function port() { $shell = "netstat -anp 2>/dev/null | grep ". self::PORT . " | grep LISTEN | wc -l"; $result = shell_exec($shell); if($result != 1) { // 发送报警服务 邮件 短信 /// todo echo date("Ymd H:i:s")."error".PHP_EOL; } else { echo date("Ymd H:i:s")."succss".PHP_EOL; } }}// nohupswoole_timer_tick(2000, function($timer_id) { (new Server())->port(); echo "time-start".PHP_EOL;});