werwolflg / yii2-wschat

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

安装: 11

依赖: 0

建议: 0

安全性: 0

星级: 0

关注者: 1

分支: 3

类型:yii2-extension

v0.1.3 2018-04-13 09:24 UTC

This package is not auto-updated.

Last update: 2024-09-22 04:54:40 UTC


README

基于Web sockets和ratchet php的在线聊天。分支:github.com/joni-jones/yii2-wschat (公共聊天,带房间)

安装

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

运行以下命令之一:

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

或者

"werwolflg/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 werwolflg\wschat\components\Chat;
      use werwolflg\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)
    

您还可以存储添加的聊天,只需指定 vent 事件的 js 回调函数

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