ghostwalker / laravelwebsocket
基于 Ratchet 的 Laravel WebSocket
dev-main
2022-09-14 17:35 UTC
Requires
- php: ^8.1
- cboden/ratchet: ^0.4.4
- nette/robot-loader: ^3.4
Requires (Dev)
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2024-09-14 21:55:21 UTC
README
您可以通过 composer 安装此包
composer require ghostwalker/laravelwebsocket
用法
注册服务提供者
在 /config/app.php 的 "providers" 数组中添加一行
Ghostwalker\LaravelWebsocketServiceProvider::class
.
然后发布配置
php artisan vendor:publish --provider="Ghostwalker\LaravelWebsocketServiceProvider" --tag="config"
.
/config/laravelwebsocket.php
示例
<?php return [ 'httphost' => 'localhost', 'port' => 8081, 'sockets_dir' => 'var/www/html/sockets', 'artisan_command_start' => 'websocket:start', ];
.
现在,在这个文件夹中,您需要创建一个类,该类将实现 MessageComponentInterface 和 AddRouteContract 接口
示例
<?php namespace Sockets; use Ghostwalker\Contracts\AddRouteContract; use Ghostwalker\LaravelWebsocket; use JetBrains\PhpStorm\Pure; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class mainSocket implements MessageComponentInterface, AddRouteContract { protected \SplObjectStorage $clients; #[Pure] public function __construct() { $this->clients = new \SplObjectStorage(); } public function onOpen(ConnectionInterface $conn) { $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(); } public static function addRout(): void { LaravelWebsocket::$app->route('/chat', new self(), array('*')); } }
在 addRout 方法中,您需要更改您套接字的路径
.
剩下的只是使用 php artisan websocket 命令启动我们的套接字服务器(作为守护进程运行的命令,它将一直运行,直到终端关闭。我推荐使用 screen)
模块
您可以创建无限数量的类,并且所有这些类都将被处理,这使得系统更加灵活
变更日志
请参阅 CHANGELOG 了解最近更改的详细信息。
贡献
请参阅 CONTRIBUTING 了解详细信息。
鸣谢
许可证
MIT 许可证 (MIT)。请参阅 许可证文件 了解更多信息。