Skip to content

Commit 32a9200

Browse files
committed
add: websocket 支持
1 parent a2eb6fd commit 32a9200

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
/**
3+
* WebSocket 服务器
4+
* User: lisgroup
5+
* Date: 19-4-2
6+
* Time: 下午 4:28
7+
*/
8+
9+
namespace App\Services;
10+
11+
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
12+
use Swoole\Http\Request;
13+
use Swoole\WebSocket\Frame;
14+
use Swoole\WebSocket\Server;
15+
16+
/**
17+
* @see https://wiki.swoole.com/wiki/page/400.html
18+
*/
19+
class WebSocketService implements WebSocketHandlerInterface
20+
{
21+
// 声明没有参数的构造函数
22+
public function __construct()
23+
{
24+
}
25+
26+
public function onOpen($server, $request)
27+
{
28+
// 在触发 onOpen 事件之前 Laravel 的生命周期已经完结,所以 Laravel 的 Request 是可读的,Session 是可读写的
29+
// \Log::info('New WebSocket connection', [$request->fd, request()->all(), session()->getId(), session('xxx'), session(['yyy' => time()])]);
30+
$i = 1;
31+
while (true) {
32+
$server->push($request->fd, 'Welcome to LaravelS'.$i);
33+
sleep(1);
34+
$i++;
35+
if ($i > 10) {
36+
break;
37+
}
38+
}
39+
// throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
40+
}
41+
42+
public function onMessage($server, $frame)
43+
{
44+
// \Log::info('Received message', [$frame->fd, $frame->data, $frame->opcode, $frame->finish]);
45+
$server->push($frame->fd, date('Y-m-d H:i:s'));
46+
// throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
47+
}
48+
49+
public function onClose($server, $fd, $reactorId)
50+
{
51+
// throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
52+
}
53+
}

laravel/config/laravels.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
'event_handlers' => [
2222
],
2323
'websocket' => [
24-
'enable' => false,
25-
//'handler' => XxxWebSocketHandler::class,
24+
'enable' => true, // 看清楚,这里是true
25+
'handler' => \App\Services\WebSocketService::class,
2626
],
2727
'sockets' => [
2828
],
@@ -46,6 +46,7 @@
4646
],
4747
'swoole' => [
4848
'daemonize' => env('LARAVELS_DAEMONIZE', false),
49+
// dispatch_mode 只能设置为 2、4、5,https://wiki.swoole.com/wiki/page/277.html
4950
'dispatch_mode' => 2,
5051
'reactor_num' => function_exists('\swoole_cpu_num') ? \swoole_cpu_num() * 2 : 4,
5152
'worker_num' => function_exists('\swoole_cpu_num') ? \swoole_cpu_num() * 2 : 8,

0 commit comments

Comments
 (0)