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>