1、下载Workerman插件
composer require topthink/think-worker
2、示例代码 后端
2.1 下载之后会得到这俩个文件
2.2 这个文件对应上面的worker_class 的地址
2.3.worker.php示例代码
<?php
namespace app\http;
use think\facade\Db;
use think\worker\Server;
use Workerman\Lib\Timer;
use app\model\IndexModel;
/**
* websockect
* Class Worker
* @package app\http
*/
class Worker extends Server
{
protected $socket = 'http://0.0.0.0:2348';
/**
* 心跳检测
* @var int
*/
protected static $heartbeat_time = 55;
public function onConnect($connection){
var_dump('connect success');
$connection->send(json_encode('connect success'));
}
## 接收消息,接收心跳消息 ,接收用户id 信息等等
public function onMessage($connection,$data)
{
$connection->lastMessageTime = time();
#var_dump($data);
$connection->send(json_encode('receive success'));
}
/**
* 消息回调
* @param $worker
* @author 冬
* @date 2022/5/5 17:07
*/
public function onWorkerStart($worker)
{
//查看是否有新的下面的3是几秒推送一次
Timer::add(3, function () use ($worker) {
$time_now = time();
var_dump(date('Y-m-d H:i:s',$time_now) );
## 推送的数据
$infoObj = IndexModel::getTips();
$infoArr = json_decode(json_encode($infoObj),true);
if (true) {
foreach ($worker->connections as $connection) {
if (empty($connection->lastMessageTime)) {
$connection->lastMessageTime = $time_now;
}
var_dump(date('Y-m-d H:i:s',$connection->lastMessageTime) );
if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) {
$connection->close();
}
$connection->send(json_encode($infoArr));
}
} else {
var_dump(22);
foreach ($worker->connections as $connection) {
if (empty($connection->lastMessageTime)) {
$connection->lastMessageTime = $time_now;
continue;
}
if ($time_now - $connection->lastMessageTime > self::$heartbeat_time) { //连接超时
$connection->close();
}
}
}
});
}
public function onClose($connection){
var_dump('close');
}
}
2.4 前端示例代码
<script>
let ws = new WebSocket("ws://127.0.0.1:2348")
ws.onopen = function() { //绑定连接事件
console.log("连接成功");
//每30秒发送一次心跳
setInterval(function(){
ws.send(JSON.stringify({'type':"peng"}));
console.log('发送心跳...');
},30000)
};
ws.onmessage = function(evt) {//绑定收到消息事件
data = JSON.parse(evt.data)
console.log(data);
//这里处理收到的消息, type类型有两种: connectin、deposit如果有deposit要提示
};
ws.onclose = function(evt) { //绑定关闭或断开连接事件
console.log("连接已关闭");
};
</script>