|
|
|
<?php
|
|
|
|
|
|
|
|
use Swoole\WebSocket\Server;
|
|
|
|
use Illuminate\Foundation\Application;
|
|
|
|
use SwooleTW\Http\Websocket\Facades\Websocket;
|
|
|
|
|
|
|
|
use App\Http\Controllers\WebSocketController;
|
|
|
|
|
|
|
|
require __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", 8888);
|
|
|
|
|
|
|
|
$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");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//调用laravel控制器
|
|
|
|
$controller = new WebSocketController();
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
$server->on('close', function ($server, $fd) {
|
|
|
|
// WebSocket 连接已关闭
|
|
|
|
echo "WebSocket 连接已关闭\n";
|
|
|
|
});
|
|
|
|
|
|
|
|
$server->start(); |
...
|
...
|
|