首先使用composer安装cboden/ratchet类包以及相关依赖
composer require cboden/ratchet
然后,创建WebsocketController控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Log;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
class WebsocketController extends Controller implements MessageComponentInterface
{
protected $clients;
public function __construct()
{
$this->clients = new \SplObjectStorage();
}
public function onOpen(ConnectionInterface $conn) {
//存储连接的websocket链接,用于待会返回消息
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client){
if($from != $client){
//发送消息给所有连接的客户端(除开发送者)
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
控制器创建完成后,使用laravel的命令行命令创建command
php artisan make:console websocket laravel:websocket
该语句会在app\console\commands目录下创建websocket.php文件
修改websocket.php
<?php
namespace App\Console\Commands;
use App\Http\Controllers\WebsocketController;
use Illuminate\Console\Command;
class Websocket extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'laravel:websocket';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
protected $app;
public function __construct()
{
parent::__construct();
//
$app = new \Ratchet\App('192.168.31.66', 2345,'0.0.0.0');
$app->route('/chat', new WebsocketController(), array('*'));
// $app->route('/echo', new \Ratchet\Server\EchoServer, array('*'));
$app->run();
}
public function handle()
{
echo "success!!";
}
}
命令创建完成后,在laravel目录根目录位置打开控制台,输入
php artisan laravel:websocket
就会开启一个独立的后台程序运行该程序
最后,前台连接websoket
var conn = new WebSocket('ws://192.168.31.66:2345/chat');
conn.onopen = function (ev) {
console.log('已连接');
};
conn.onerror = function(){
setTimeout(connected,2000);
};
conn.onmessage = function(){
};
至此,一个简单的websocket应用就实现了,可以实现简单的全屏通知