s4studio/yii2-wschat

基于 WebSocket 和 ratchet php 的私有聊天(Yii2)

安装: 101

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 3

类型:yii2-extension

0.2 2018-10-25 11:57 UTC

This package is auto-updated.

Last update: 2024-09-28 18:10:51 UTC


README

基于 WebSocket 和 ratchet php 的在线聊天。Forked: https://github.com/svbackend/yii2-wschat(公开聊天,有房间)。去除了MongoDB依赖项。

安装

安装此扩展的首选方式是通过 composer

运行

php composer.phar require --prefer-dist s4studio/yii2-wschat

或添加

"s4studio/yii2-wschat": "*"

到你的 composer.json 文件的 require 部分。

使用方法

  1. 聊天扩展可以使用 Yii 支持的任何数据库存储。

    如果你想使用 mysql/mariadb 服务器,保持你的当前数据库配置,并简单地导入表

        CREATE TABLE IF NOT EXISTS `history` (
          `id` int(11) NOT NULL,
          `chat_id` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `chat_title` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `user_id` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `username` varchar(60) COLLATE utf8_unicode_ci DEFAULT NULL,
          `avatar_16` varchar(90) COLLATE utf8_unicode_ci DEFAULT NULL,
          `avatar_32` varchar(90) COLLATE utf8_unicode_ci DEFAULT NULL,
          `timestamp` int(11) NOT NULL DEFAULT '0',
          `message` text COLLATE utf8_unicode_ci
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
        
        ALTER TABLE `history`
          ADD PRIMARY KEY (`id`);
        
        ALTER TABLE `history`
          MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

    如果指定了 mongodb 扩展,聊天将尝试将其用作消息历史存储,否则将使用应用程序配置中 db 组件中指定的扩展。

    以下列出了一个如何使用 mongodb 存储的简单示例。安装 MongoDByii2-mongodb 扩展以存储消息历史,你只需要在 console 配置中指定连接。

        'components' => [
            'mongodb' => [
                'class' => '\yii\mongodb\Connection',
                'dsn' => 'mongodb://username:password@localhost:27017/dbname'
            ]
        ]

    在创建的 mongodb 数据库中,你需要创建一个名为 history 的集合;

  2. 要启动聊天服务器,需要创建控制台命令并将其设置为守护进程

    • 创建一个继承自 yii\console\Controller 的控制器

      ServerController extends \yii\console\Controller
    • 创建一个启动服务器的操作

      namespace app\commands;
      
      use s4studio\wschat\components\Chat;
      use s4studio\wschat\components\ChatManager;
      use Ratchet\Server\IoServer;
      use Ratchet\Http\HttpServer;
      use Ratchet\WebSocket\WsServer;
      
      class ServerController extends \yii\console\Controller
      {
          public function actionRun()
          {
              $manager = Yii::configure(new ChatManager(), [
                  'userClassName' => Users::class, // Your User Active Record model class
              ]);
              $server = IoServer::factory(new HttpServer(new WsServer(new Chat($manager))), 8080);
      
              // If there no connections for a long time - db connection will be closed and new users will get the error
              // so u need to keep connection alive like that
              // Что бы база данных не разрывала соединения изза неактивности
              $server->loop->addPeriodicTimer(60, function () use ($server) {
                  try{
                      Yii::$app->db->createCommand("DO 1")->execute();
                  }catch (Exception $e){
                      Yii::$app->db->close();
                      Yii::$app->db->open();
                  }
                  // Also u can send messages to your cliens right there
                  /*
                  foreach ($server->app->clients as $client) {
                      $client->send("hello client");
                  }*/
              });
      
              $server->run();
              echo 'Server was started successfully. Setup logging to get more details.'.PHP_EOL;
          }
      }
    • 现在,你可以使用 yii 控制台命令来运行聊天服务器

      yii server/run
  3. 要在页面上添加聊天,只需调用

        <?= ChatWidget::widget([
            'auth' => true,
            'user_id' => Yii::$app->user->id // setup id of current logged user
        ]) ?>
     List of available options:
     auth - boolean, default: false
     user_id - mixed, default: null
     port - integer, default: 8080
     chatList - array (allow to set list of preloaded chats), default: [
         id => 1,
         title => 'All'
     ],
     add_room - boolean, default: true (allow to user create new chat rooms)
    

你也可以存储添加的聊天,只需指定 js 回调函数来处理 vent 事件

Chat.vent('chat:add', function(chatModel) {
    console.log(chatModel);
});

此代码片段可以在你的代码中添加,但必须在聊天小部件加载之后。在回调中,你将可以访问到 Chat.Models.ChatRoom backbone 模型。现在,你需要添加你的代码来保存聊天室而不是 console.log()

如果 YII_DEBUG 已启用 - 所有 js 脚本都将单独加载。

默认情况下,聊天将尝试从资源文件夹加载两张图片:/avatar_16.png/avatar_32.png

可能的问题

如果你在控制台日志中看不到任何消息,请检查你的日志配置组件的 flushIntervalexportInterval。简单的配置可能如下所示

'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'flushInterval' => 1,
    'targets' => [
        [
            'class' => 'yii\log\FileTarget',
            'levels' => ['error', 'warning', 'info'],
            'logVars' => [],
            'exportInterval' => 1
        ],
    ],
],

许可证

MIT