websocket_server.php
1.5 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
<?php
use Swoole\WebSocket\Server;
use Illuminate\Foundation\Application;
require_once __DIR__ . '/vendor/autoload.php';
$app = new Application(__DIR__);
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
Illuminate\Foundation\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
Illuminate\Foundation\Exceptions\Handler::class
);
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$server = new Server("0.0.0.0", 9555);
$server->on('open', function ($server, $request) {
// WebSocket 连接已打开
echo "WebSocket 连接已打开\n";
});
$server->on('message', function ($server, $frame) {
$message = $frame->data;
echo "收到消息: $message\n";
// 获取客户端连接的文件描述符
$fd = $frame->fd;
// 回复消息给客户端
$response = "我已收到消息: $message";
$server->push($fd, $response);
// 获取所有客户端连接的文件描述符
$clients = $server->connection_list();
// 迭代所有客户端连接并广播消息
foreach ($clients as $fd) {
// 排除自己,避免回发消息给发送者
if ($fd !== $frame->fd) {
$server->push($fd, "这是广播消息: $message");
}
}
});
$server->on('close', function ($server, $fd) {
// WebSocket 连接已关闭
echo "WebSocket 连接已关闭\n";
});
echo '启用成功';
$server->start();