用了一下感觉很棒,但是目前不知道怎么在项目中起websocket服务…之前自己用laravel做简单聊天室是在commands里面写的swoole websockt服务,但是感觉这个框架应该不是这样起的,求大佬指导
创建一个websocket类并实现WebSocketHandlerInterface 接口
namespace App\Services;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
/**
* @see https://www.swoole.co.uk/docs/modules/swoole-websocket-server
*/
class WebSocketService implements WebSocketHandlerInterface
{
// Declare constructor without parameters
public function __construct()
{
}
public function onOpen(\swoole_websocket_server $server, \swoole_http_request $request)
{
// Laravel has finished its lifetime before triggering onOpen event, so Laravel's Request & Session are available here.
\Log::info('New Websocket connection', [$request->fd, request()->all(), session()->getId(), session('xxx')]);
$server->push($request->fd, 'Welcome to LaravelS');
// throw new \Exception('an exception');// all exceptions will be ignored, then record them into Swoole log, you need to try/catch them
}
public function onMessage(\swoole_websocket_server $server, \swoole_websocket_frame $frame)
{
\Log::info('Received message', [$frame->fd, $frame->data, $frame->opcode, $frame->finish]);
$server->push($frame->fd, date('Y-m-d H:i:s'));
// throw new \Exception('an exception');// all exceptions will be ignored, then record them into Swoole log, you need to try/catch them
}
public function onClose(\swoole_websocket_server $server, $fd, $reactorId)
{
// throw new \Exception('an exception');// all exceptions will be ignored, then record them into Swoole log, you need to try/catch them
}
}
更改配置文件 config/laravels.php
// ...
'websocket' => [
'enable' => true,
'handler' => \App\Services\WebSocketService::class,
],
'swoole' => [
//...
// Must set dispatch_mode in (2, 4, 5), see https://www.swoole.co.uk/docs/modules/swoole-server/configuration
'dispatch_mode' => 2,
//...
],
// ...
…
中文文档 https://github.com/hhxsv5/laravel-s/blob/master/README-CN.md#启用websocket服务器
配置完之后应该就随应用启动了吧。
已解决,是我太菜没有看文档,谢谢大佬