laravel+workerman(ws)

<?php

namespace App\Console\Commands;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Illuminate\Console\Command;
use Workerman\Worker;

class WorkermanWebs extends Command
{
    protected $signature = 'wk:webs  {action} {--d}';
    protected $description = 'workerman websockets';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        global $argv;
        $action = $this->argument('action');
        $argv[0] = 'wk:webs';
        $argv[1] = $action;
        $argv[2] = $this->option('d') ? '-d' : '';
        $this->start();
    }

    private function start()
    {
        $this->startGateWay();
        $this->startBusinessWorker();
        $this->startRegister();
        Worker::runAll();
    }

    private function startBusinessWorker()
    {
        $worker                  = new BusinessWorker();
        $worker->name            = 'BusinessWorker';
        $worker->count           = 1;
        $worker->registerAddress = '127.0.0.1:1236';
        $worker->eventHandler    = \App\Workerman\Events::class;

    }

    private function startGateWay()
    {
        $gateway = new Gateway("websocket://0.0.0.0:8088");
        $gateway->name                 = 'Gateway';
        $gateway->count                = 1;
        $gateway->lanIp                = '0.0.0.0';
        $gateway->startPort            = 2300;
        $gateway->pingInterval         = 30;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = '{"type":"@heart@"}';
        $gateway->registerAddress      = '127.0.0.1:1236';
    }

    private function startRegister()
    {
        new Register('text://0.0.0.0:1236');
    }
}
<?php


namespace App\Workerman;


use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;

class Events
{
    public static function onWorkerStart($businessWorker)
    {
        echo "onWorkerStart\r\n";
    }

    public static function onConnect($client_id)
    {
        Gateway::sendToClient($client_id, json_encode(['type' => 'onConnect', 'client_id' => $client_id]));
        echo "onConnect\r\n";

    }

    public static function onWebSocketConnect($client_id, $data)
    {
        echo "onWebSocketConnect\r\n";
    }

    public static function onMessage($client_id, $message)
    {
        $data = json_decode($message, true);
        if (isset($data['imei'])) Gateway::bindUid($client_id, $data['imei']);
        Gateway::sendToClient($client_id, json_encode(['type' => 'onMessage', 'client_id' => $client_id]));
        echo "onMessage\r\n";

    }

    public static function onClose($client_id)
    {
        echo "onClose\r\n";
    }

}
<?php


namespace App\Http\Controllers;


use App\Events\SendUid;
use App\Workerman\Events;
use GatewayClient\Gateway;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;


class TestController extends Controller
{
    public function index(Request $request)
    {
        $uid = $request->get('uid');
        try {
            Gateway::$registerAddress = 'xx.xx.xx.xx:1236';
//            $arr = Gateway::getClientIdByUid($uid);
//            Log::info($arr);
//            Log::info('$arr');
//            if(count($arr) >0)
            Gateway::sendToUid($uid, json_encode(['type' => 'onHhx', 'message' => 'success']));
            return true;
        } catch (\Exception $exception) {
            Log::info($exception->getMessage());
        }
    }
}
stream_socket_client(): unable to connect to tcp://0.0.0.0:xxxx (Connection refused)

修改GatewayClient文件

在stream_socket_client()之前将地址改过来

文件vendor/workerman/gatewayclient/Gateway.php的1186行下添加如下代码

$address = str_replace('0.0.0.0', explode(':', self::$registerAddress)[0], $address);
要使用Laravel8和Swoole实现直播,你需要遵循以下步骤: 1. 首先,你需要在Laravel项目中安装Swoole扩展。可以使用Composer运行以下命令来安装它: ``` composer require swooletw/laravel-swoole ``` 2. 在项目的`config/app.php`文件中添加以下行,将Swoole提供程序添加到Laravel中: ``` 'providers' => [ ... SwooleTW\Http\LaravelServiceProvider::class, ... ], 'aliases' => [ ... 'Swoole' => SwooleTW\Http\Facades\Swoole::class, ... ], ``` 3. 创建Swoole服务器的配置文件。可以在项目的根目录下创建`swoole.php`文件,并添加以下内容: ``` return [ 'host' => env('SWOOLE_HOST', '127.0.0.1'), 'port' => env('SWOOLE_PORT', '9501'), 'options' => [ 'worker_num' => 8, 'daemonize' => env('SWOOLE_DAEMONIZE', false), 'task_worker_num' => 8, ], ]; ``` 4. 在`.env`文件中添加以下行,以使用上述配置: ``` SWOOLE_HOST=127.0.0.1 SWOOLE_PORT=9501 SWOOLE_DAEMONIZE=false ``` 5. 创建一个Swoole服务器的启动脚本。在项目的`app/Console/Commands`目录下创建一个`SwooleServer.php`脚本,并添加以下内容: ``` <?php namespace App\Console\Commands; use Illuminate\Console\Command; use SwooleTW\Http\Server\Facades\Server; class SwooleServer extends Command { protected $signature = 'swoole:server {action}'; protected $description = 'Start or stop swoole http server.'; public function handle() { $action = $this->argument('action'); if ($action === 'start') { Server::start(); } elseif ($action === 'stop') { Server::stop(); } else { $this->error('Invalid argument.'); } } } ``` 6. 创建控制器来处理直播流。在项目中创建一个控制器,例如`LiveController.php`,并添加以下内容: ``` <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use SwooleTW\Http\Websocket\Facades\Websocket; class LiveController extends Controller { public function index(Request $request) { return view('live.index'); } public function handle(Request $request) { // 处理直播流 Websocket::broadcast()->emit('live', $request->getContent()); } } ``` 7. 创建一个WebSocket事件监听器。在项目的`app/Providers`目录下创建一个`WebsocketServiceProvider.php`文件,并添加以下内容: ``` <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use SwooleTW\Http\Websocket\Server; use App\Events\LiveStream; class WebsocketServiceProvider extends ServiceProvider { public function boot(Server $server) { $server->on('message', function ($server, $frame) { $payload = json_decode($frame->data, true); if ($payload['event'] === 'live') { event(new LiveStream($payload['data'])); } }); } } ``` 8. 创建一个事件类来处理直播流。在项目中创建一个事件类,例如`LiveStream.php`,并添加以下内容: ``` <?php namespace App\Events; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class LiveStream { use Dispatchable, InteractsWithSockets, SerializesModels; public $stream; public function __construct($stream) { $this->stream = $stream; } public function broadcastOn() { return ['live']; } } ``` 9. 创建一个事件监听器来推送直播流。在项目的`app/Listeners`目录下创建一个`LiveStreamListener.php`文件,并添加以下内容: ``` <?php namespace App\Listeners; use App\Events\LiveStream; use SwooleTW\Http\Websocket\Facades\Websocket; class LiveStreamListener { public function handle(LiveStream $event) { Websocket::broadcast()->emit('live', $event->stream); } } ``` 10. 在`EventServiceProvider.php`中注册事件和监听器。在项目的`app/Providers`目录下找到`EventServiceProvider.php`文件,并将以下行添加到`$listen`数组中: ``` 'App\Events\LiveStream' => [ 'App\Listeners\LiveStreamListener', ], ``` 11. 创建一个前端页面来显示直播流。在项目的`resources/views`目录下创建一个`live/index.blade.php`文件,并添加以下内容: ``` <!DOCTYPE html> <html> <head> <title>Live Stream</title> <meta name="csrf-token" content="{{ csrf_token() }}"> </head> <body> <div id="live"></div> <script src="{{ asset('js/app.js') }}"></script> <script> const ws = new WebSocket('ws://localhost:9501'); ws.onmessage = function (event) { const data = JSON.parse(event.data); if (data.event === 'live') { document.getElementById('live').innerHTML = data.data; } }; </script> </body> </html> ``` 现在你已经完成了Laravel8和Swoole的配置,可以使用以上步骤来实现直播功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值