1、swoole的安裝php
參照官網:https://wiki.swoole.com/wiki/page/6.htmlhtml
2、代碼部分react
服務端:服務器
<?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.\n"; }); //監聽數據接收事件 $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.\n"; }); //啓動服務器 $serv->start();
客戶端:swoole
<?php // 鏈接 tcp server服務器 $client = new swoole_client(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', 9501)) { exit("connect failed. Error: {$client->errCode}\n"); } // php cli常量 fwrite(STDIN, "請輸入消息:"); $msg = trim(fgets(STDOUT)); // 發送消息get tcp server 服務器 $client->send("{$msg}\n"); // 接收來自server的數據 echo $result = $client->recv(); $client->close();
也可經過 命令行:socket
# telnet 127.0.0.1 9501tcp
進行測試測試