laravel+swoole 实现websocket(php+web 双向通信)

1.环境配置

安装swoole扩展(这里使用的是宝塔开启)
php.ini 增加 extension=swoole.so

实现流程
1.swoole创建socket服务
2.web连接socket完成订阅发布
3.php连接socket完成订阅发布

2.文件创建
#app/Console/Commands
php artisan make:command Socket
#在Kernel.php里增加命令列表
Commands\Socket::Class
3.运行socket服务

php artisan socket

<?php

namespace App\Console\Commands;

use App\Model\Ws;
use Illuminate\Console\Command;

class Socket extends Command
{
    public $ws;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'socket';

    /**
     * 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()
    {
        //
        $this->start();
    }

    public function start()
    {
        //创建websocket服务器对象,监听0.0.0.0:7104端口
        $this->ws = new \swoole_websocket_server("0.0.0.0", 7104);

        //监听WebSocket连接打开事件
        $this->ws->on('open', function ($ws, $request) {
            var_dump($request->fd . "连接成功");
            // $ws->push($request->fd, "hello, welcome\n");
        });

        //监听WebSocket消息事件
        $this->ws->on('message', function ($ws, $frame) {
            echo $frame->fd . "________{$frame->data}\n";
            $ws->push($frame->fd, "server: {$frame->data}");
			
			//收到消息 广播所有人
            $clients = $this->ws->getClientList();
            $clientId = [];
            foreach ($clients as $value) {
                $clientId[] = $value;
            }
            echo json_encode($clientId);
            if (!empty($clientId)) {
                foreach ($clientId as $v) {
                    $this->ws->push($v, time());
                }
            }
        });

        //监听WebSocket连接关闭事件
        $this->ws->on('close', function ($ws, $fd) {
            echo "client:{$fd} is closed\n";
        });
        $this->ws->start();
    }
}

4.web页面连接
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="msglist"></div>
<div>
    <input type="text" id="msg" placeholder="请输入">
    <button id="send">发送消息</button>
</div>
</body>
</html>
<script>
    //客户端连接WebSocket服务器端
    const ws = new WebSocket('ws://192.168.36.3:7104');

    //事件监听
    ws.onopen = () => {
        console.log('连接成功');
    };
    
    //解构赋值
    ws.onmessage = ({data}) => {
        console.log('接收数据',data);
    };

    //关闭事件
    ws.onclose = () => {
        console.log('服务器断开连接')
    };

    //mvp操作  dom操作
    let msglist = document.querySelector('#msglist');
    let msg = document.querySelector('#msg');
    let send = document.querySelector('#send');

    send.onclick = () => {
        let data = msg.value;
        msg.value = '';
        ws.send(data);
    };
</script>
5.PHP连接
#php 连接socket扩展 https://github.com/Textalk/websocket-php
#composer require textalk/websocket 

use WebSocket\Client;

 $options = [
            'uri' => 'ws://192.168.36.3:7104',
            'opcode' => 'text'
        ];
        $message = time();
        $client = new Client($options['uri'], $options);
        $client->send($message, $options['opcode']);
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值