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#%E5%90%AF%E7%94%A8websocket%E6%9C%8D%E5%8A%A1%E5%99%A8
配置完之后应该就随应用启动了吧。
创建一个websocket类并实现WebSocketHandlerInterface 接口
更改配置文件
config/laravels.php
...
https://github.com/hhxsv5/laravel-s#enable-websocket-server
恩,我再试下,多谢。
😂
加上/之后就没办法排除data了,不知道为什么。
但是多了一层目录出来。在project_bak目录下生成了一个project。
谢谢大神,确实可以用。