**
后台代码
**`<?php
namespace app\apiMoblie\home;
use app\common\controller\Common;
use Workerman\Worker;
use app\apiMoblie\home\Qrcodeserver;
class Index extends Common
{
public function index()
{
// return $this->fetch();
//创建一个Worker监听2346端口,使用websocket协议通讯
$ws_worker = new Worker(“websocket://0.0.0.0:2346”);
// 启动4个进程对外提供服务
$ws_worker->count = 4;
// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data)
{
// 向客户端发送hello $data
$connection->send('hello 低调低调哈哈哈' . $data);
};
// 运行worker
$aa = Worker::runAll();
// halt($aa);
}
/**
* 直接输出二维码 + 生成二维码图片文件
*/
public function create(){
// 自定义二维码配置
$config = [
'title' => true,
'title_content' => 'test',
'logo' => true,
'logo_url' => './logo.jpg',
'logo_size' => 80,
];
// 直接输出
$qr_url = 'http://www.chmqlive.com/?id=' . rand(1000, 9999);
$qr_code = new QrcodeServer($config);
$qr_img = $qr_code->createServer($qr_url);
echo $qr_img;
// 写入文件
$qr_url = '这是个测试二维码';
$file_name = './static/qrcode'; // 定义保存目录
$config['file_name'] = $file_name;
$config['generate'] = 'writefile';
$qr_code = new QrcodeServer($config);
$rs = $qr_code->createServer($qr_url);
print_r($rs);
exit;
}
public function add_timer(){
echo 1;
Timer::add(1, array($this, 'indexs'), array(), true);
}
public function indexs(){
file_put_contents("1.txt", json_encode(2)."|".PHP_EOL,FILE_APPEND);
echo 333;
if(time()>1){
echo 222;
}
}
}
**
前端html代码`
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<body>
<script>
//ws = new WebSocket("ws://127.0.0.1:2346");
ws = new WebSocket("ws://worker.net:2346");
ws.onopen = function() {
alert("连接成功");
ws.send('tom');
alert("给服务端发送一个字符串:tom");
};
ws.onmessage = function(e) {
console.log(e);
alert("收到服务端的消息:" + e.data);
};
</script>
</body>
</html>
**
CMD 运行代码