1. Go to this page and download the library: Download s4studio/yii2-wschat library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?phprequire_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespaceapp\commands;
uses4studio\wschat\components\Chat;
uses4studio\wschat\components\ChatManager;
useRatchet\Server\IoServer;
useRatchet\Http\HttpServer;
useRatchet\WebSocket\WsServer;
classServerControllerextends \yii\console\Controller{
publicfunctionactionRun(){
$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 server/run
<?= ChatWidget::widget([
'auth' => true,
'user_id' => Yii::$app->user->id // setup id of current logged user
])