thinkphp8扩展think-swoole4.0-事件监听代码

首先服务端配置监听

swoole.php

<?php

return [
    'http'       => [
        'enable'     => true,
        'host'       => '0.0.0.0',
        'port'       => 8000,
        'worker_num' => swoole_cpu_num(),
        'options'    => [],
    ],
    'websocket'  => [
        'enable'        => true,
        'handler'       => \think\swoole\websocket\Handler::class,
        'ping_interval' => 25000,
        'ping_timeout'  => 60000,
        'room'          => [
            'type'  => 'table',
            'table' => [
                'room_rows'   => 8192,
                'room_size'   => 2048,
                'client_rows' => 4096,
                'client_size' => 2048,
            ],
            'redis' => [
                'host'          => '127.0.0.1',
                'port'          => 6379,
                'max_active'    => 3,
                'max_wait_time' => 5,
            ],
        ],
        'listen'        => [
               // 'connect' => \app\listener\WsConnect::class,
                'close' => 'app\listener\WsClose',//关闭事件
                // 'test' => \app\listener\WsTest::class
               'event' => \app\listener\WebsocketTest::class,//事件监听
            ],
        'subscribe'     => [],
    ],
    'rpc'        => [
        'server' => [
            'enable'     => false,
            'host'       => '0.0.0.0',
            'port'       => 9000,
            'worker_num' => swoole_cpu_num(),
            'services'   => [],
        ],
        'client' => [],
    ],
    //队列
    'queue'      => [
        'enable'  => false,
        'workers' => [],
    ],
    'hot_update' => [
        'enable'  => env('APP_DEBUG', false),
        'name'    => ['*.php'],
        'include' => [app_path()],
        'exclude' => [],
    ],
    //连接池
    'pool'       => [
        'db'    => [
            'enable'        => true,
            'max_active'    => 3,
            'max_wait_time' => 5,
        ],
        'cache' => [
            'enable'        => true,
            'max_active'    => 3,
            'max_wait_time' => 5,
        ],
        //自定义连接池
    ],
    'ipc'        => [
        'type'  => 'unix_socket',
        'redis' => [
            'host'          => '127.0.0.1',
            'port'          => 6379,
            'max_active'    => 3,
            'max_wait_time' => 5,
        ],
    ],
    'tables'     => [],
    //每个worker里需要预加载以共用的实例
    'concretes'  => [],
    //重置器
    'resetters'  => [],
    //每次请求前需要清空的实例
    'instances'  => [],
    //每次请求前需要重新执行的服务
    'services'   => [],
];

WebsocketTest.php

<?php
declare (strict_types = 1);
namespace app\listener;
use think\Container;
use think\swoole\Websocket;

class WebsocketTest
{
	public $websocket = null;
	public function __construct(Container  $container){
		$this->websocket = $container->make(Websocket::class);
	}
	/**
	 * 事件监听处理
	 * @param $event
	 */
	public function handle($event)
	{
        echo '接收到事件,' . $event->type . '---' . $event->data;
        echo '--------';
        var_dump($event);


       // echo $this->websocket->getSender();//客户端标识
        
        // $this->websocket->emit('callback', 'my response');//向客户端发送消息 //客户端接收消息"{\"type\":\"callback\",\"data\":[\"my response\"]}"
        //  $this->websocket->to('0.2')->emit('callback2', 'my response2');//向其他客户端发送消息 0.2是客户端得getSender()
        // $this->websocket->broadcast()->emit('test_callback','这是一条广播消息');//服务端发送广播消息  高版本Websocket类中没有broadcast这个函数


        // //分房间,方便分组发消息管理
        // $room = app('think\swoole\websocket\Room');
        // var_dump($room->getClients('room1'));//输出房间内信息
        // $this->websocket->join('room1');//加入房间
        // // $this->websocket->setSender(fd)->join('room1');//将其他客户端加入房间
        // var_dump($room->getClients('room1'));

        // $this->websocket->leave(['room1']);//离开房间

        //给房间内成员发送消息
        // $this->websocket->to('roomName')->emit('callback2', 'my response2');
        // $this->websocket->to(['roomName1','roomName2','roomName3'])->emit('callback2', 'my response2');

        // var_dump($room->getClients('room1'));

		$func = $event->type;
		$this->$func($event);
	}
	
	/**
	 * 测试类型
	 * @param $event
	 */
	public function test($event)
	{
		$msg = json_encode($event->data,256);
		$this->websocket->emit('callback', $msg);
	}
}

WsClose.php

<?php
declare (strict_types = 1);

namespace app\listener;

class WsClose
{
    /**
     * 事件监听处理
     *
     * @return mixed
     */
    public function handle($event)
    {
        //
        echo '已经断开了';
    }
}

页面客户端代码

<html>
<head>
<title>websocket</title>

</head>

<body>
<h1>websocket功能</h1>

<input id="msg" type="text"/>
<button onclick="send()">发送</button>

<script>
    var ws = new WebSocket("ws://192.168.50.114:8000");

	ws.onopen = function (){
        console.log("连接成功");
        var sendObj = {};
        sendObj.type = 'connect';
        sendObj.data = 'connect success';

        console.log('msg',JSON.stringify(sendObj));

        ws.send(JSON.stringify(sendObj));
    }
	
	ws.onclose = function () {
        console.log("连接失败")
    }

	ws.onmessage = function (evt) {
        console.log("数据已接收",evt);
    }

    function send(){
        console.log('运行到这里了');
        var msg = document.getElementById('msg').value;
      
        var sendObj = {};
        sendObj.type = 'mtest';
        sendObj.data = msg;

        console.log('msg',JSON.stringify(sendObj));

        ws.send(JSON.stringify(sendObj));
    }
</script>
</body>

</html>

测试截图

能够处理连接、断开、发送消息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liberty888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值