thinkphp8扩展think-swoole4.0

配置文件 config/swoole.php#

<?php
//默认\think\swoole\websocket\Handler::class,
use think\swoole\websocket\socketio\Handler;
return [
    'http'       => [
        'enable'     => true,//开启
        'host'       => '0.0.0.0',
        'port'       => 9501,
        'worker_num' => swoole_cpu_num(),
        'options'    => [],
    ],
    'websocket'  => [
        'enable'        => true,//开启
        'handler'       => 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'        => [
			'event' => \app\listener\WebsocketTest::class,//事件监听
			
		],
        'subscribe'     => [],
    ],
   
];

事件监听app\listener\WebsocketTest#

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

前端#

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.socket.io/socket.io-1.4.4.js"></script>
</head>
<body>
<script>
    var socket = io('http://IP:9501',{transports: ['websocket']});
    //对应事件 以及消息
    socket.emit("test",{"asd":"我是内容"})
    //回调事件
    socket.on('callback',(data)=>{
        console.log('data',data);
    });
</script>
</body>
</html>



启动swoole#

php think swoole

作者:douyuanjun

出处:https://www.cnblogs.com/douyuanjun/p/18053789

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   窦戈  阅读(685)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
more_horiz
keyboard_arrow_up dark_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示