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配置)
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!"}}}')
升级中, 可能继续新增http session, auth, 丰富配置, 以及简化web app向swoole worker投递异步任务机制...