fastadmin CMS部署workerman
基础文档:Workerman · ThinkPHP5.0完全开发手册 · 看云
在线测试地址:EasySwoole-WebSocket在线测试工具
一、安装扩展包 composer require topthink/think-worker
遇到报错:不能安装,参考:tp5 workerman安装不上解决方法 – 知乎
直接执行:composer require topthink/think-worker=1.0.* 即可成功
二、新建 server.php
#!/usr/bin/env php
<?php
define('APP_PATH', __DIR__ . '/application/');
define('BIND_MODULE','push/Worker');
// 加载框架引导文件
require __DIR__ . '/thinkphp/start.php';
三、新建Worker.php php think make:controller push/Worker 即可,将里面的内容替换如下所示:
<?php
namespace app\push\controller;
use think\Controller;
use think\Request;
use think\worker\Server;
use think\Cache;
class Worker extends Server
{
protected $socket = 'websocket://0.0.0.0:2346';
protected $processes = 1;
protected $uidConnections = array();
static $count = 0;
/**
* 收到信息
* @param $connection
* @param $data
*/
public function onMessage($connection, $data)
{
$retdata=json_decode($data,true);
$uid=$retdata['id'];
$message=$retdata['msg'];
if(isset($this->uidConnections[$uid]))
{
$connection = $this->uidConnections[$uid];
$connection->send($message);
// return true;
}
$connection->send('我收到你的信息了333='.$retdata['msg']);
}
/**
* 当连接建立时触发的回调函数
* @param $connection
*/
public function onConnect($connection)
{
$this->uidConnections[$connection->id] = $connection;
$connection->send('你连接了我='.$connection->id);
}
// 针对uid推送数据
public function sendMessageByUid($uid, $message)
{
if(isset($this->uidConnections[$uid]))
{
$connection = $this->uidConnections[$uid];
$connection->send($message);
return true;
}
return false;
}
/**
* 当连接断开时触发的回调函数
* @param $connection
*/
public function onClose($connection)
{
}
/**
* 当客户端的连接上发生错误时触发
* @param $connection
* @param $code
* @param $msg
*/
public function onError($connection, $code, $msg)
{
echo "error $code $msg\n";
}
/**
* 每个进程启动
* @param $worker
*/
public function onWorkerStart($worker)
{
}
}
四、执行 php server.php start 遇到禁用函数就去对应的PHP里面把禁用函数删除 (此命令可以放到Supervisor的守护进程里面去),并且查看端口是否运行,宝塔里面也要放行对应的端口 2346
五、前端代码
<!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://118.**.***.207:2346");
ws.onopen = function() {
console.log("连接成功");
ws.send('tom');
console.log("给服务端发送一个字符串:tom");
};
ws.onmessage = function(e) {
console.log("收到服务端的消息:" + e.data);
};
</script>
</body>
</html>
六、前端开两个端口即可进行相互通讯:
ws.send('{"id":"2","msg":"21111111111110"}');
一条评论
发表新评论
- Pingback: fastadmin部署workerman 找不到指定栏目
