欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > thinkphp8.0\swoole的websocket应用

thinkphp8.0\swoole的websocket应用

2025/3/26 5:56:23 来源:https://blog.csdn.net/quweiie/article/details/146481115  浏览:    关键词:thinkphp8.0\swoole的websocket应用

环境:centOS7.9、php8.3、thinkphp8.0\think-swoole4.1

我用的官方think-swoole插件

第一步:根据官方文档,需要安装此扩展插件

composer require topthink/think-swoole

第二步:在根目录下config文件夹下编辑swoole.php配置文件

    'http'=> ['enable'     => true,'host'       => '0.0.0.0', // 任意ip都可以访问http服务;'port'       => 8080, // 宝塔和阿里云、腾讯云的安全组需要开放此端口;'worker_num' => swoole_cpu_num(),'options'    => ['daemonize' =>  true], // 守护进程运行],'websocket'  => ['enable'        => true, // 默认为false, 一定要开启'route' => false,  // 最大的坑,在做测试时,一定要关闭,否则调试不出结果;'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'        => ['event' => \app\index\listener\WebsocketTest::class,//事件监听'close' => 'app\index\listener\WsClose',//关闭事件],'subscribe'     => [],],

第三步:我的框架是多应用模式,我创建了index应用;

// WebsocketTest.php; 路径: app\index\listener
namespace app\index\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);$func = $event->type;$this->$func($event);}/*** 测试类型* @param $event*/public function test($event){$msg = json_encode($event->data,256);$this->websocket->emit('callback', $msg);}
}

第四步:websocket关闭事件

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

第五步:前端index.html

<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://你的ip:8080");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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词