https://github.com/immusen/yii2-swoole-websocketphp
示例:git
聊天室案例, 示例代碼: /websocket/controllers/RoomController.phpgithub
發送消息:web
{ "jsonrpc":"2.0", "id":1, "method":"room/msg", "params":{ "id":"100111", "content":{ "text":"Hello world!" } } }
聊天室成員接收消息:redis
{ "jsonrpc":"2.0", "id":1, "result":{ "text":"Hello world!" } }
開發:json
1, 在websocket/controllers目錄下建立Controller, (也能夠是其它路徑, 只需修改config/main.php中controllerNamespace配置)服務器
<?php namespace websocket\controllers; use immusen\websocket\src\Controller; class FooController extends Controller { public function actionBar($param_1, $param_2 = 0, param_n = null) { # addFds把當前客戶端fd存儲到一個集合, $param_1做爲Key(其它字符串亦可) $this->addFds($this->fd, $param_1); # 向當前websocket客戶端發送信息 $this->publish($this->fd, ['p1' => param_1, 'p2' => param_2]); # 從集合中取出全部客戶度fd $fds_array = $this->getFds($param_1); # 羣發消息給集合中的客戶端 $this->publish($fds_array, ['p1' => param_1, 'p2' => param_2]); # 經過redis鏈接池操做redis $this->redis->set($param_1, 0) } public function actionBaz() { //... } }
2, 發送JSONRPC, 並指定method爲"foo/bar", 並經過params傳遞相應參數便可調用上述actionwebsocket
{ "jsonrpc":"2.0", "id":1, "method":"foo/bar", "params":{ "param_1":"client_01", "param_2":100, "param_n":{ "time":1551408888, "type":"report" } } }
全部的客戶端到服務器的RPC調用, 除用websocket客戶端以外, 也能夠使用HTTP或Redis Publish來投遞, 該特性能夠用於Yii Web應用向Swoole worker投遞異步任務(例如發短信..), 在聊天室例子中, 能夠這樣操做:swoole
HTTP 請求:yii2
http://127.0.0.1:8721/rpc?p={"jsonrpc":"2.0","id":1,"method":"room/msg","params":{"id":"100111","content":{"text":"System warning!"}}}
或 redis-cli:
127.0.0.1:6379> publish rpc '{"jsonrpc":"2.0","id":1,"method":"room/msg","params":{"id":"100111","content":{"text":"System warning!"}}}'
或 在Yii web 應用中
Yii:$app->redis->publish('rpc', '{"jsonrpc":"2.0","id":1,"method":"room/msg","params":{"id":"100111","content":{"text":"System warning!"}}}')
或經過Hook(推薦方式), 支持runOnce, 確保任務即便在多Swoole實例的狀況下只執行一次, 詳見immusen/yii2-swoole-websocket/Hook.php
Yii::$app->hook->run('room/msg', ['id' => 100111, 'content' => ['text' => 'System warning!']]); Yii::$app->hook->runOnce('sms/send', ['mobile' => 15600008721, 'code' => '8721']);
新升級:啓動腳本支持更多操做
./websocket-server {start|restart|reload|stop|status}
./websocket-server status master_pid=7404 start_time=1554030075 connection_num=130 accept_count=1025767 close_count=1025637 tasking_num=123 request_count=2051456 worker_request_count=511103 coroutine_num=2