-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.php
More file actions
1072 lines (928 loc) · 38.1 KB
/
Copy pathserver.php
File metadata and controls
1072 lines (928 loc) · 38.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env php
<?php
declare(strict_types=1);
/**
* server.php
* Workerman wrapper for FSSPHP with WebSocket support
*
* Usage:
* php server.php start - Start in debug mode (foreground)
* php server.php start -d - Start in daemon mode (background)
* php server.php stop - Stop server
* php server.php restart - Restart server
* php server.php reload - Reload business logic
* php server.php status - Show server status
* php server.php connections - Show connections
*
* Services:
* - HTTP Server: http://0.0.0.0:8000
* - WebSocket Server: ws://0.0.0.0:1234 (or wss:// with SSL)
*/
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request as WorkermanRequest;
use Workerman\Protocols\Http\Response as WorkermanResponse;
use Workerman\Timer;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Framework\Core\Framework;
use Framework\Schema\SchemaWarmup;
use Framework\Schema\SchemaRegistry;
use Framework\Utils\WorkermanHealth;
use Framework\Pool\RedisPool;
use Framework\Pool\MysqlPool;
use Framework\Pool\PoolManager;
use Framework\Queue\RedisConsumerService;
use App\Queue\Handlers\DefaultMessageHandler;
use App\Queue\Handlers\ArticleMessageHandler;
// 只允许 CLI 模式运行
if (php_sapi_name() !== 'cli') {
return;
}
define('WORKERMAN_ENV', true);
define('BASE_PATH', __DIR__);
define('APP_ROOT', __DIR__);
define('LOG_DIR', APP_ROOT . '/storage/workerman');
define('HEALTH_FILE', LOG_DIR . '/health.json');
define('WS_LOG_FILE', LOG_DIR . '/websocket.log');
// 创建日志目录
if (!is_dir(LOG_DIR)) {
mkdir(LOG_DIR, 0777, true);
}
const MEMORY_LIMIT_MB = 256;
const MEMORY_CHECK_INTERVAL = 10;
require_once __DIR__ . '/vendor/autoload.php';
// 设置日志文件
Worker::$logFile = LOG_DIR . '/workerman.log';
// ----------------------------------------------------------------------
// 日志工具
// ----------------------------------------------------------------------
function log_info(string $msg): void {
$line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
file_put_contents(LOG_DIR . '/server.log', $line, FILE_APPEND);
}
function ws_log(string $msg): void {
$line = '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
file_put_contents(WS_LOG_FILE, $line, FILE_APPEND);
}
// ----------------------------------------------------------------------
// 健康检查与日志轮转
// ----------------------------------------------------------------------
function update_health(?Worker $worker = null): void {
$snapshot = WorkermanHealth::snapshot($worker?->id, $worker?->name);
WorkermanHealth::writeHealthFile(HEALTH_FILE, $snapshot);
WorkermanHealth::appendMemoryHistory(LOG_DIR, $snapshot, $worker?->name ?? 'http');
}
function rotate_logs(): void {
$files = [
LOG_DIR . '/server.log',
WS_LOG_FILE
];
foreach ($files as $file) {
if (file_exists($file) && filesize($file) > 2 * 1024 * 1024) {
$new = LOG_DIR . '/' . basename($file, '.log') . '-' . date('Ymd_His') . '.log';
rename($file, $new);
log_info("[LogRotate] Rotated to $new");
}
}
}
// ----------------------------------------------------------------------
// Symfony Request / Response 转换
// ----------------------------------------------------------------------
function convert_to_workerman_response(SymfonyResponse $res): WorkermanResponse {
$headers = [];
foreach ($res->headers->allPreserveCase() as $name => $values) {
if (strtolower($name) === 'set-cookie') {
$headers[$name] = $values;
} else {
$headers[$name] = is_array($values) ? implode(', ', $values) : $values;
}
}
$content = $res->getContent();
// 移除可能存在的 Content-Length 头,让 Workerman 自动计算
if (isset($headers['content-length'])) {
unset($headers['content-length']);
}
return new WorkermanResponse($res->getStatusCode(), $headers, $content);
}
/**
* 将 Workerman Request 转换为 Symfony Request
*/
function convert_to_symfony_request(WorkermanRequest $request): SymfonyRequest
{
$method = strtoupper($request->method());
$uri = $request->uri();
$rawBody = $request->rawBody();
$remoteIp = $request->connection?->getRemoteIp() ?? '127.0.0.1';
$remotePort = $request->connection?->getRemotePort() ?? 0;
$uriParts = parse_url($uri);
$pathInfo = $uriParts['path'] ?? '/';
$queryString = $uriParts['query'] ?? '';
$get = $request->get() ?? [];
if (!empty($queryString)) {
parse_str($queryString, $queryParams);
$get = array_merge($queryParams, $get);
}
$post = $request->post() ?? [];
$cookies = $request->cookie() ?? [];
// 处理上传文件
$symfonyFiles = [];
$wmFiles = $request->file() ?? [];
foreach ($wmFiles as $field => $fileInfo) {
// 单文件
if (isset($fileInfo['tmp_name'])) {
if (!empty($fileInfo['tmp_name']) && file_exists($fileInfo['tmp_name'])) {
$symfonyFiles[$field] = new UploadedFile(
$fileInfo['tmp_name'],
$fileInfo['name'] ?? '',
$fileInfo['type'] ?? null,
$fileInfo['error'] ?? UPLOAD_ERR_OK,
true
);
}
continue;
}
// 多文件
if (is_array($fileInfo)) {
$files = [];
foreach ($fileInfo as $index => $item) {
if (!isset($item['tmp_name']) || empty($item['tmp_name']) || !file_exists($item['tmp_name'])) {
continue;
}
$files[$index] = new UploadedFile(
$item['tmp_name'],
$item['name'] ?? '',
$item['type'] ?? null,
$item['error'] ?? UPLOAD_ERR_OK,
true
);
}
if ($files) {
$symfonyFiles[$field] = $files;
}
}
}
$headers = $request->header() ?? [];
$parameters = array_merge($get, $post);
$server = [
'REQUEST_METHOD' => $method,
'REQUEST_URI' => $uri,
'PATH_INFO' => $pathInfo,
'QUERY_STRING' => $queryString,
'REMOTE_ADDR' => $remoteIp,
'REMOTE_PORT' => $remotePort,
'SERVER_PROTOCOL' => 'HTTP/1.1',
'HTTP_HOST' => $headers['host'] ?? 'localhost',
'CONTENT_LENGTH' => $headers['content-length'] ?? strlen($rawBody),
'CONTENT_TYPE' => $headers['content-type'] ?? '',
'PHP_SELF' => $pathInfo,
'SCRIPT_NAME' => $pathInfo,
'SCRIPT_FILENAME' => '',
];
foreach ($headers as $name => $value) {
$key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
$server[$key] = is_array($value) ? implode(', ', $value) : $value;
}
if (!isset($server['HTTP_X_FORWARDED_FOR'])) {
$server['HTTP_X_FORWARDED_FOR'] = $remoteIp;
}
if (in_array($method, ['PUT', 'DELETE', 'PATCH']) && empty($post) && !empty($rawBody)) {
parse_str($rawBody, $parsedPost);
$post = array_merge($post, $parsedPost);
}
return new SymfonyRequest(
$get,
$post,
[],
$cookies,
$symfonyFiles,
$server,
$rawBody
);
}
/**
* 获取文件的 MIME 类型
*/
function get_mime_type(string $filePath): string
{
$mimeTypes = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'svg' => 'image/svg+xml',
'ico' => 'image/x-icon',
'bmp' => 'image/bmp',
'mp4' => 'video/mp4',
'webm' => 'video/webm',
'ogg' => 'video/ogg',
'mp3' => 'audio/mpeg',
'wav' => 'audio/wav',
'pdf' => 'application/pdf',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'txt' => 'text/plain',
'html' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'zip' => 'application/zip',
'rar' => 'application/vnd.rar',
'7z' => 'application/x-7z-compressed',
'tar' => 'application/x-tar',
'gz' => 'application/gzip',
'woff' => 'font/woff',
'woff2' => 'font/woff2',
'ttf' => 'font/ttf',
'eot' => 'application/vnd.ms-fontobject',
];
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
return $mimeTypes[$extension] ?? 'application/octet-stream';
}
// ----------------------------------------------------------------------
// WebSocket 连接管理器
// ----------------------------------------------------------------------
class WebSocketManager
{
private static ?WebSocketManager $instance = null;
private array $connections = []; // 存储所有连接
private array $rooms = []; // 存储房间信息
public static function getInstance(): WebSocketManager
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 添加连接
*/
public function addConnection(TcpConnection $connection): void
{
$this->connections[$connection->id] = [
'connection' => $connection,
'user_id' => null,
'rooms' => [],
'data' => [],
'connected_at' => time()
];
ws_log("[WS] Connection #{$connection->id} added. Total: " . count($this->connections));
}
/**
* 移除连接
*/
public function removeConnection(TcpConnection $connection): void
{
$connId = $connection->id;
if (isset($this->connections[$connId])) {
// 从所有房间中移除
foreach ($this->connections[$connId]['rooms'] as $roomId) {
$this->leaveRoom($connection, $roomId);
}
unset($this->connections[$connId]);
ws_log("[WS] Connection #{$connId} removed. Total: " . count($this->connections));
}
}
/**
* 绑定用户ID
*/
public function bindUser(TcpConnection $connection, $userId): void
{
if (isset($this->connections[$connection->id])) {
$this->connections[$connection->id]['user_id'] = $userId;
ws_log("[WS] Connection #{$connection->id} bound to user #{$userId}");
}
}
/**
* 加入房间
*/
public function joinRoom(TcpConnection $connection, string $roomId): void
{
if (!isset($this->connections[$connection->id])) {
return;
}
// 添加到房间的连接列表
if (!isset($this->rooms[$roomId])) {
$this->rooms[$roomId] = [];
}
$this->rooms[$roomId][$connection->id] = true;
// 添加到连接的房间列表
$this->connections[$connection->id]['rooms'][$roomId] = true;
ws_log("[WS] Connection #{$connection->id} joined room '{$roomId}'. Room size: " . count($this->rooms[$roomId]));
}
/**
* 离开房间
*/
public function leaveRoom(TcpConnection $connection, string $roomId): void
{
if (!isset($this->connections[$connection->id])) {
return;
}
// 从房间中移除
if (isset($this->rooms[$roomId][$connection->id])) {
unset($this->rooms[$roomId][$connection->id]);
if (empty($this->rooms[$roomId])) {
unset($this->rooms[$roomId]);
}
}
// 从连接的房间列表中移除
unset($this->connections[$connection->id]['rooms'][$roomId]);
ws_log("[WS] Connection #{$connection->id} left room '{$roomId}'");
}
/**
* 发送消息给指定连接
*/
public function sendToConnection(TcpConnection $connection, array $data): void
{
$connection->send(json_encode($data, JSON_UNESCAPED_UNICODE));
}
/**
* 发送消息给指定用户
*/
public function sendToUser($userId, array $data): int
{
$count = 0;
foreach ($this->connections as $connData) {
if ($connData['user_id'] === $userId) {
$connData['connection']->send(json_encode($data, JSON_UNESCAPED_UNICODE));
$count++;
}
}
return $count;
}
/**
* 发送消息到房间
*/
public function sendToRoom(string $roomId, array $data, ?TcpConnection $exclude = null): int
{
if (!isset($this->rooms[$roomId])) {
return 0;
}
$count = 0;
$message = json_encode($data, JSON_UNESCAPED_UNICODE);
foreach ($this->rooms[$roomId] as $connId => $true) {
if ($exclude && $connId === $exclude->id) {
continue;
}
if (isset($this->connections[$connId])) {
$this->connections[$connId]['connection']->send($message);
$count++;
}
}
return $count;
}
/**
* 广播消息给所有连接
*/
public function broadcast(array $data, ?TcpConnection $exclude = null): int
{
$count = 0;
$message = json_encode($data, JSON_UNESCAPED_UNICODE);
foreach ($this->connections as $connId => $connData) {
if ($exclude && $connId === $exclude->id) {
continue;
}
$connData['connection']->send($message);
$count++;
}
return $count;
}
/**
* 获取在线连接数
*/
public function getOnlineCount(): int
{
return count($this->connections);
}
/**
* 获取房间信息
*/
public function getRoomInfo(string $roomId): ?array
{
if (!isset($this->rooms[$roomId])) {
return null;
}
$connections = [];
foreach ($this->rooms[$roomId] as $connId => $true) {
if (isset($this->connections[$connId])) {
$connections[] = [
'id' => $connId,
'user_id' => $this->connections[$connId]['user_id'],
'connected_at' => $this->connections[$connId]['connected_at']
];
}
}
return [
'room_id' => $roomId,
'count' => count($connections),
'connections' => $connections
];
}
/**
* 获取所有房间
*/
public function getAllRooms(): array
{
return array_keys($this->rooms);
}
}
// ----------------------------------------------------------------------
// 创建 HTTP Worker
// ----------------------------------------------------------------------
$httpWorker = new Worker('http://0.0.0.0:8000');
$httpWorker->name = 'FSSPHP-HTTP';
$httpWorker->count = 4;
// 存储 Framework 实例
$framework = null;
// ----------------------------------------------------------------------
// HTTP Worker 启动回调
// ----------------------------------------------------------------------
$httpWorker->onWorkerStart = function(Worker $worker) use (&$framework) {
log_info("[HTTP-Worker] PID " . getmypid() . " started");
Worker::log("[HTTP-Worker] PID " . getmypid() . " started");
update_health();
// 初始化框架
$framework = Framework::getInstance();
// Schema 预热
if (defined('WORKERMAN_ENV')) {
SchemaWarmup::setScanPath(base_path('app/Models'), 'App\Models');
SchemaWarmup::ignore([
\App\Models\TempView::class,
]);
SchemaWarmup::warmupAll();
SchemaRegistry::freeze();
}
// ---------------------------------------------------------------
// 连接池初始化(每个 Worker 进程独立持有,不跨进程共享)
// ---------------------------------------------------------------
try {
$redisConfig = require BASE_PATH . '/config/redis.php';
$databaseConfig = require BASE_PATH . '/config/database.php';
// --- Redis 连接池 ---
if (!empty($redisConfig['pool']['enabled'])) {
$primaryNode = $redisConfig['nodes'][0] ?? [];
$redisPoolConfig = array_merge($primaryNode, $redisConfig['pool']);
PoolManager::register('redis.default', new RedisPool($redisPoolConfig));
log_info(sprintf(
'[HTTP-Worker #%d] Redis 连接池已初始化,空闲:%d / 最大:%d',
$worker->id,
$redisPoolConfig['min_connections'] ?? 2,
$redisPoolConfig['max_connections'] ?? 10
));
}
// --- MySQL 连接池 ---
if (!empty($databaseConfig['pool']['enabled'])) {
$mysqlConn = $databaseConfig['connections']['mysql'] ?? [];
$mysqlPoolConfig = array_merge([
'host' => $mysqlConn['hostname'] ?? '127.0.0.1',
'port' => (int) ($mysqlConn['hostport'] ?? 3306),
'database' => $mysqlConn['database'] ?? 'fssoa',
'username' => $mysqlConn['username'] ?? 'root',
'password' => $mysqlConn['password'] ?? '',
'charset' => $mysqlConn['charset'] ?? 'utf8mb4',
], $databaseConfig['pool']);
PoolManager::register('mysql.default', new MysqlPool($mysqlPoolConfig));
log_info(sprintf(
'[HTTP-Worker #%d] MySQL 连接池已初始化,空闲:%d / 最大:%d',
$worker->id,
$mysqlPoolConfig['min_connections'] ?? 2,
$mysqlPoolConfig['max_connections'] ?? 10
));
}
} catch (\Throwable $e) {
log_info('[HTTP-Worker] 连接池初始化失败(降级为直连):' . $e->getMessage());
}
// 定时任务:内存监控、日志轮转、健康检查
Timer::add(MEMORY_CHECK_INTERVAL, function() use ($worker) {
update_health($worker);
rotate_logs();
$pid = getmypid();
$time = date('Y-m-d H:i:s');
$memoryReal = memory_get_usage(true) / 1048576;
$memoryEmalloc = memory_get_usage(false) / 1048576;
$includedFiles = count(get_included_files());
$classes = count(get_declared_classes());
$interfaces = count(get_declared_interfaces());
$traits = count(get_declared_traits());
$objects = (function() {
$count = 0;
foreach (get_defined_vars() as $v) is_object($v) && $count++;
return $count;
})();
Worker::log("[{$time}] [Memory] HTTP-Worker #{$worker->id} PID {$pid} "
. "real:{$memoryReal}MB emalloc:{$memoryEmalloc}MB "
. "files:{$includedFiles} classes:{$classes} "
. "interfaces:{$interfaces} traits:{$traits}");
// 连接池统计日志
$poolStats = PoolManager::stats();
if (!empty($poolStats)) {
$statStr = implode(' ', array_map(
fn($n, $s) => "{$n}[idle:{$s['idle']} active:{$s['active']} max:{$s['max']}]",
array_keys($poolStats),
$poolStats
));
Worker::log("[{$time}] [Pool] HTTP-Worker #{$worker->id} {$statStr}");
}
// 内存超限则重启
if ($memoryReal > MEMORY_LIMIT_MB) {
Worker::log("[{$time}] [Warning] HTTP-Worker #{$worker->id} PID {$pid} memory exceeded limit ({$memoryReal} MB > " . MEMORY_LIMIT_MB . " MB), stopping...");
$worker->stop();
}
});
};
// ----------------------------------------------------------------------
// HTTP Worker 停止回调(关闭连接池)
// ----------------------------------------------------------------------
$httpWorker->onWorkerStop = function(Worker $worker) {
log_info(sprintf('[HTTP-Worker #%d] 正在关闭连接池...', $worker->id));
PoolManager::closeAll();
log_info(sprintf('[HTTP-Worker #%d] 连接池已关闭', $worker->id));
};
// ----------------------------------------------------------------------
// HTTP 请求处理回调
// ----------------------------------------------------------------------
$httpWorker->onMessage = function(TcpConnection $connection, WorkermanRequest $req) use (&$framework) {
$symReq = null;
$symRes = null;
try {
// ==================== 静态文件处理 ====================
$uri = $req->uri();
$pathInfo = parse_url($uri, PHP_URL_PATH);
$staticDirs = ['/uploads', '/assets', '/css', '/js', '/images', '/favicon.ico'];
$isStaticFile = false;
foreach ($staticDirs as $dir) {
if (strpos($pathInfo, $dir) === 0) {
$isStaticFile = true;
break;
}
}
if ($isStaticFile) {
$filePath = __DIR__ . '/public' . $pathInfo;
$realPath = realpath($filePath);
$publicDir = realpath(__DIR__ . '/public');
if ($realPath && strpos($realPath, $publicDir) === 0 && is_file($realPath)) {
$contentType = get_mime_type($realPath);
$fileContent = file_get_contents($realPath);
$headers = [
'Content-Type' => $contentType,
'Cache-Control' => 'public, max-age=86400',
];
if (preg_match('/\.(jpg|jpeg|png|gif|webp|svg|ico)$/i', $realPath)) {
$headers['Cache-Control'] = 'public, max-age=2592000';
}
$connection->send(new WorkermanResponse(200, $headers, $fileContent));
return;
}
$connection->send(new WorkermanResponse(404, ['Content-Type' => 'text/plain'], 'File Not Found'));
return;
}
// ==================== 静态文件处理结束 ====================
// 健康检查端点
if ($req->path() === '/_health') {
update_health();
$data = file_get_contents(HEALTH_FILE);
$response = new SymfonyResponse($data, 200, ['Content-Type' => 'application/json']);
$connection->send(convert_to_workerman_response($response));
return;
}
// WebSocket 统计信息端点
if ($req->path() === '/_ws-stats') {
$wsManager = WebSocketManager::getInstance();
$stats = [
'online_count' => $wsManager->getOnlineCount(),
'rooms' => $wsManager->getAllRooms(),
'time' => date('Y-m-d H:i:s')
];
$response = new SymfonyResponse(json_encode($stats), 200, ['Content-Type' => 'application/json']);
$connection->send(convert_to_workerman_response($response));
return;
}
// 转换请求并处理
$symReq = convert_to_symfony_request($req);
$symRes = $framework->handleRequest($symReq);
// 保存 Session 并清理内存,防止跨请求累积
if ($symReq->hasSession()) {
$session = $symReq->getSession();
$session->save();
$session->clear();
}
// 发送队列中的 Cookie
app('cookie')->sendQueuedCookies($symRes);
$connection->send(convert_to_workerman_response($symRes));
} catch (Throwable $e) {
$error = "[Error] {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}";
log_info($error);
Worker::log($error);
$connection->send(new WorkermanResponse(500, [], "Internal Error: {$e->getMessage()}"));
} finally {
// 清理资源:Request/Response + Session 内存
if (isset($symReq) && $symReq->hasSession()) {
$symReq->getSession()->clear();
}
unset($symReq, $symRes);
gc_collect_cycles();
}
};
// ----------------------------------------------------------------------
// 创建 WebSocket Worker (ws://0.0.0.0:1234)
// ----------------------------------------------------------------------
$wsWorker = new Worker('websocket://0.0.0.0:1234');
$wsWorker->name = 'FSSPHP-WebSocket';
$wsWorker->count = 1;
// 如果需要 SSL/TLS (wss://),取消下面的注释并配置证书路径
/*
$wsWorker->transport = 'ssl';
$wsWorker->context = [
'ssl' => [
'local_cert' => '/path/to/your/cert.pem',
'local_pk' => '/path/to/your/private.key',
'verify_peer' => false,
]
];
*/
// ----------------------------------------------------------------------
// WebSocket Worker 启动回调
// ----------------------------------------------------------------------
$wsWorker->onWorkerStart = function(Worker $worker) {
ws_log("[WS-Worker] PID " . getmypid() . " started");
Worker::log("[WS-Worker] PID " . getmypid() . " started");
// 心跳检测定时器
Timer::add(55, function() use ($worker) {
$wsManager = WebSocketManager::getInstance();
$time = date('Y-m-d H:i:s');
foreach ($worker->connections as $connection) {
// 如果上次心跳时间超过 120 秒,则关闭连接
if (empty($connection->lastHeartbeatTime)) {
$connection->lastHeartbeatTime = time();
} elseif (time() - $connection->lastHeartbeatTime > 120) {
ws_log("[WS] Connection #{$connection->id} timeout, closing");
$connection->close();
continue;
}
// 发送心跳包
$connection->send(json_encode(['type' => 'ping']));
}
ws_log("[{$time}] [WS-Heartbeat] Online: " . $wsManager->getOnlineCount());
});
};
// ----------------------------------------------------------------------
// WebSocket 连接建立回调
// ----------------------------------------------------------------------
$wsWorker->onConnect = function(TcpConnection $connection) {
$connection->lastHeartbeatTime = time();
$wsManager = WebSocketManager::getInstance();
$wsManager->addConnection($connection);
ws_log("[WS] New connection #{$connection->id} from {$connection->getRemoteIp()}");
// 发送欢迎消息
$wsManager->sendToConnection($connection, [
'type' => 'connected',
'data' => [
'connection_id' => $connection->id,
'message' => 'Welcome to FSSPHP WebSocket Server',
'time' => date('Y-m-d H:i:s')
]
]);
};
// ----------------------------------------------------------------------
// WebSocket 消息接收回调
// ----------------------------------------------------------------------
$wsWorker->onMessage = function(TcpConnection $connection, string $data) {
$wsManager = WebSocketManager::getInstance();
try {
// 更新心跳时间
$connection->lastHeartbeatTime = time();
// 解析消息
$message = json_decode($data, true);
if (!$message || !isset($message['type'])) {
$wsManager->sendToConnection($connection, [
'type' => 'error',
'data' => ['message' => 'Invalid message format']
]);
return;
}
$type = $message['type'];
$payload = $message['data'] ?? [];
ws_log("[WS] Received message type '{$type}' from connection #{$connection->id}");
// 根据消息类型处理
switch ($type) {
case 'pong':
// 心跳响应,已更新心跳时间
break;
case 'bind':
// 绑定用户ID
if (isset($payload['user_id'])) {
$wsManager->bindUser($connection, $payload['user_id']);
$wsManager->sendToConnection($connection, [
'type' => 'bind_success',
'data' => ['user_id' => $payload['user_id']]
]);
}
break;
case 'join':
// 加入房间
if (isset($payload['room_id'])) {
$wsManager->joinRoom($connection, $payload['room_id']);
// 通知房间内其他人
$wsManager->sendToRoom($payload['room_id'], [
'type' => 'user_joined',
'data' => [
'connection_id' => $connection->id,
'room_id' => $payload['room_id']
]
], $connection);
// 发送确认给当前连接
$wsManager->sendToConnection($connection, [
'type' => 'join_success',
'data' => ['room_id' => $payload['room_id']]
]);
}
break;
case 'leave':
// 离开房间
if (isset($payload['room_id'])) {
$wsManager->leaveRoom($connection, $payload['room_id']);
// 通知房间内其他人
$wsManager->sendToRoom($payload['room_id'], [
'type' => 'user_left',
'data' => [
'connection_id' => $connection->id,
'room_id' => $payload['room_id']
]
], $connection);
// 发送确认给当前连接
$wsManager->sendToConnection($connection, [
'type' => 'leave_success',
'data' => ['room_id' => $payload['room_id']]
]);
}
break;
case 'message':
// 发送消息到房间
if (isset($payload['room_id']) && isset($payload['content'])) {
$wsManager->sendToRoom($payload['room_id'], [
'type' => 'message',
'data' => [
'connection_id' => $connection->id,
'room_id' => $payload['room_id'],
'content' => $payload['content'],
'time' => date('Y-m-d H:i:s')
]
]);
}
break;
case 'broadcast':
// 广播消息
$count = $wsManager->broadcast([
'type' => 'broadcast',
'data' => [
'connection_id' => $connection->id,
'content' => $payload['content'] ?? '',
'time' => date('Y-m-d H:i:s')
]
], $connection);
$wsManager->sendToConnection($connection, [
'type' => 'broadcast_success',
'data' => ['sent_to' => $count]
]);
break;
case 'private_message':
// 私聊消息
if (isset($payload['user_id']) && isset($payload['content'])) {
$count = $wsManager->sendToUser($payload['user_id'], [
'type' => 'private_message',
'data' => [
'from_connection_id' => $connection->id,
'content' => $payload['content'],
'time' => date('Y-m-d H:i:s')
]
]);
$wsManager->sendToConnection($connection, [
'type' => 'private_message_sent',
'data' => [
'user_id' => $payload['user_id'],
'delivered' => $count > 0
]
]);
}
break;
case 'get_room_info':
// 获取房间信息
if (isset($payload['room_id'])) {
$roomInfo = $wsManager->getRoomInfo($payload['room_id']);
$wsManager->sendToConnection($connection, [
'type' => 'room_info',
'data' => $roomInfo
]);
}
break;
case 'get_online_count':
// 获取在线人数
$wsManager->sendToConnection($connection, [
'type' => 'online_count',
'data' => ['count' => $wsManager->getOnlineCount()]
]);
break;
default:
// 未知消息类型
$wsManager->sendToConnection($connection, [
'type' => 'error',
'data' => ['message' => "Unknown message type: {$type}"]
]);
}
} catch (Throwable $e) {
ws_log("[WS-Error] {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}");
$wsManager->sendToConnection($connection, [
'type' => 'error',
'data' => ['message' => 'Internal server error']
]);
}
};
// ----------------------------------------------------------------------
// WebSocket 连接关闭回调
// ----------------------------------------------------------------------
$wsWorker->onClose = function(TcpConnection $connection) {
$wsManager = WebSocketManager::getInstance();
$wsManager->removeConnection($connection);
ws_log("[WS] Connection #{$connection->id} closed");
};
// ----------------------------------------------------------------------
// WebSocket 错误回调
// ----------------------------------------------------------------------
$wsWorker->onError = function(TcpConnection $connection, $code, $msg) {
ws_log("[WS-Error] Connection #{$connection->id} error: {$code} - {$msg}");
};
// ----------------------------------------------------------------------
// 队列消费 Worker(独立进程,避免阻塞 http/wss 业务流)
// ----------------------------------------------------------------------
$redisConfigForQueue = require __DIR__ . '/config/redis.php';