侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

centos7+laravel7+swooletw/laravel-swoole扩展包的使用流程步骤及简单的websocket服务测试

Laravel  /  管理员 发布于 4年前   2960

centos7+laravel7+swooletw/laravel-swoole扩展包的使用流程步骤及简单的websocket服务测试

这篇也是可以接上一篇的,因为我测试都是用同一个环境,使用之前的文章都可以无缝连接

这边是centos7+laravel7+swooletw/laravel-swoole扩展的使用,了解一下长连接,并搭建websocket服务器测试,

看过之前的文章的都知道swoole等依赖都安装好了


开始安装swooletw/laravel-swoole

[root@www laraveltest]# composer require swooletw/laravel-swoole -vvv
Reading ./composer.json
Loading config file /root/.config/composer/config.json
Loading config file /root/.config/composer/auth.json
Loading config file ./composer.json
。。。。
Discovered Package: swooletw/laravel-swoole
Package manifest generated successfully.

我们创建一个服务 自定义Artisan Commnad自行搜索

在 app\Console\Command\ 目录下生成 Swoole 文件

[root@www laraveltest]# php artisan make:command Swoole
Console command created successfully.

App\Console\Commands\Swoole.php

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use swoole_websocket_server;
class Swoole extends Command
{
    /**
     * The name and signature of the console command.
     * @var string
     */
    protected $signature = 'swoole {action}';
    /**
     * The console command description.
     * @var string
     */
    protected $description = 'Command description';
    /**
     * Create a new command instance.
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Execute the console command.
     * 服务命令
     * @return mixed
     */
    public function handle()
    {
        $action = $this->argument('action');
        switch ($action) {
            case 'close':
                break;
            default:
                $this->start();
                break;
        }
    }
    /**
     * 创建websocket服务器对象,监听0.0.0.0:9502端口
     * 具体可参考 https://wiki.swoole.com/#/start/start_tcp_server
     */
    public function start()
    {
        // 这里是监听的服务端口号
        $this->ws = new swoole_websocket_server("0.0.0.0", 9502);
        //监听WebSocket连接打开事件
        $this->ws->on('open', function ($ws, $request) {
            var_dump($request->fd, $request->get, $request->server);
            $ws->push($request->fd, "hello, welcome\n:我的博客:https://www.zongscan.com/\n");
        });
        //监听WebSocket消息事件
        $this->ws->on('message', function ($ws, $frame) {
            $this->info("client is SendMessage:172.18.1.230\n" . $frame);
        });
        //监听WebSocket主动推送消息事件
        $this->ws->on('request', function ($request, $response) {
            $scene = $request->post['scene'];
            foreach ($this->ws->connections as $fd) {
                if ($this->ws->isEstablished($fd)) {
                    $this->ws->push($fd, $scene);
                }
            }
        });
        //监听WebSocket连接关闭事件
        $this->ws->on('close', function ($ws, $fd) {
            $this->info("client is close\n");
        });
        $this->ws->start();
    }
}

在App\Console\Kernel.php文件中注册Swoole.php里面的Swoole类

<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     * @var array
     */
    protected $commands = [
        //
        \App\Console\Commands\Swoole::class,
    ];
    /**
     * Define the application's command schedule.
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        // $schedule->command('inspire')->hourly();
    }
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
        require base_path('routes/console.php');
    }
}

这Swoole服务就写好了,我们去启动它:php artisan swoole start

看一下进程启动了没(0 0.0.0.0:9502)

[root@www ~]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      16451/mysqld        
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      4460/redis-server 1 
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      8462/nginx: master  
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      4420/sshd           
tcp        0      0 0.0.0.0:9502            0.0.0.0:*               LISTEN      1696/php            
tcp6       0      0 :::22                   :::*                    LISTEN      4420/sshd


测试

添加路由:

Route::get('/sock', 'SockController@index');

创建控制器:SockController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SockController extends Controller
{
    public function index(){
        return view('sock');
    }
}

创建模板:sock.blade.php

<!doctype html>
<html>
<head>
<title>测试WebSocket</title>
</head>
<div id="WebSocket"></div>
<body>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script>
    (function(){
        var ws = new WebSocket("ws://172.18.1.230:9502");
        ws.onopen = function(event) {
            console.log("客户端已连接上!");
            ws.send("hello server,this is client!"); //客户端给服务端推送消息
        };
        ws.onmessage = function(event) {
            var parent = document.getElementById('WebSocket');
            var div = document.createElement("div");
            div.innerHTML = event.data
            parent.appendChild(div);
            console.log("服务器传过来的数据是:" + event.data);
        }
        ws.onclose = function(event) {
            console.log("连接已关闭");
        };
    })()
</script>
</body>

看看效果

1.png


  • 上一条:
    centos7+laravel7+Passport 帮你快速实现api认证
    下一条:
    保持Laravel路由井井有条,条理分明,整齐不乱的3种方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • Laravel 11.14版本发布 - 新的字符串助手和ServeCommand改进(0个评论)
    • Laravel 11.12版本发布 - Artisan的`make`命令自动剪切`.php `扩展(0个评论)
    • Laravel的轻量型购物车扩展包:binafy/laravel-cart(0个评论)
    • Laravel 11.11版本发布 - 查看模型中的第三方关系:show(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-01
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客