tp5.1+think-swoole启用踩坑记录
1.先安装swoole(宝塔扩展可以直接安装)
pecl install swoole
2.查看是否安装成功
php -m
3.使用官方扩展swoole2.0 直接composer安装think_swoole
地址:https://www.kancloud.cn/manual/thinkphp5_1/675277
进入tp根目录执行
composer require topthink/think-swoole=2.0.* #不支持windows
4.服务器安全组开放,配置开放端口(宝塔在安全里面开放)
5.具体的看上面文档,我只是记录
自定义类:
<?php namespace app\http; use think\swoole\Server; class Swoole extends Server { protected static $token; protected $host = '0.0.0.0'; protected $port = 9508; protected $serverType = 'socket'; protected static $uid = ''; protected $option = [ 'worker_num' => 4, // 设置启动的Worker进程数 'daemonize' => false, //守护进程化。 'backlog' => 128, //Listen队列长度, 'dispatch_mode' => 2, // 'heartbeat_check_interval' => 5, // 延时 // 'heartbeat_idle_time' => 100, // 心跳 ]; // public function onRequest($request, $response) // { // var_dump('qweqw'); // } public function onOpen( $server, $req) { $server->push($req->fd, json_encode("{$req->fd}连接成功")); } public function onMessage($server, $frame) { $data = json_decode($frame->data,true); switch($data['type']){ case 'xiaohu': $server->push($frame->fd,json_encode(['type'=>'say1','message'=>"hello,小虎收到收到,有屁就放,大哥忙的横"],true)); var_dump(json_encode(['type'=>'say1','message'=>"hello,小虎收到收到,有屁就放,大哥忙的横"],true)); break; case 'xiaohusay': $server->push($frame->fd,json_encode(['type'=>'init','message'=>"NMMP,你脑袋才有病,SB"],true)); break; default: $server->push($frame->fd,json_encode(['type'=>'other','message'=>'一群SB'],true)); } } function onClose(\swoole_server $server, int $fd, int $reactorId) { var_dump(1111); } }
'swoole_class' => 'app\http\Swoole' 这个自定义类配置
前端:
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> $(function () { //判断浏览器是否支持WebSocket var supportsWebSockets = 'WebSocket' in window || 'MozWebSocket' in window; if (supportsWebSockets) { //建立WebSocket连接(ip地址换成自己主机ip) var ws = new WebSocket("ws://114.116.113.219:9508"); ws.onopen = function () { console.log("服务器连接成功,呼叫虎哥呼叫呼叫 overover"); ws.send('{"type":"xiaohu"}') }; ws.onerror = function () { console.log("服务器连接失败。。"); }; ws.onmessage = function (evt) { var data = JSON.parse(evt.data) switch(data.type){ case 'say1': if(content == ''){ console.log('请你先输入你想骂他的话,谢谢');return false; } ws.send(JSON.stringify({ 'type': 'say1', 'message' : content })) } }; ws.onclose = function (res) { console.log("websocket连接已关闭") }; }else{ console.log("您的浏览器不支持 WebSocket!"); } }); </script>
小demo,光放的自定义类放上去一直报错,踩坑无数
- 版权申明:此文如未标注转载均为本站原创,自由转载请表明出处《龙行博客》。
- 本文网址:https://www.liaotaoo.cn/316.html
- 上篇文章:了解阻塞模式和非阻塞模式
- 下篇文章:随机数生成类