0

https://github.com/immusen/yii2-swoole-websocket

示例:

聊天室案例, 示例代码: /websocket/controllers/RoomController.php

发送消息:

{
        "jsonrpc":"2.0",
        "id":1,
        "method":"room/msg",
        "params":{
            "id":"100111",
            "content":{
                "text":"Hello world!"
            }
        }
    }

聊天室成员接收消息:

{
        "jsonrpc":"2.0",
        "id":1,
        "result":{
            "text":"Hello world!"
        }
    }

开发:

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传递相应参数即可调用上述action

    {
        "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投递异步任务(例如发短信..), 在聊天室例子中, 可以这样操作:

HTTP 请求:

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

你可能感兴趣的

载入中...