Compare commits

..

16 Commits

Author SHA1 Message Date
05c5014829 2026-04-20-1
Some checks failed
Build and Release / build (push) Failing after 3m40s
Build and Release / release (push) Has been skipped
project_version=4.4.14.19
* 修复clear指令构建命令时抛出转型异常导致无法正确发送指令
* 修复ChangePolicy增加和减小index写反的问题
2026-04-20 23:26:41 +08:00
4bb276a755 docs(更新日志): 版本号更新
Some checks failed
Build and Release / build (push) Failing after 3h5m53s
Build and Release / release (push) Has been cancelled
2026-02-01 10:22:54 +08:00
ea04a3e9fc refactor(提取接口): 提取了Client/Server类的方法接口 2026-01-31 19:24:03 +08:00
748474de86 fix(优化import): 优化import 2025-09-29 16:56:40 +08:00
8f822b1983 fix(优化import): 优化import 2025-09-29 16:56:03 +08:00
8ac6e8a305 feat(新增操作handler): * 新增操作ServerOperation类中方法会话建立Handler,已在与客户端会话创建后可进行操作 * 修改错误消息提醒 2025-09-29 16:55:02 +08:00
de25eb9011 feat(对操作类增加错误参数): 对操作类增加错误参数
* 添加操作Operation类的Error方法错误的参数,同时移除无参方法

BREAKING CHANGE: 移除了Operation错误方法的无参实现
2025-09-23 20:00:51 +08:00
5c4dd0dcdd feat(添加支持): 添加服务器对SSL密码参数支持 2025-09-21 22:50:22 +08:00
c8ae336116 feat(扩展字段): 添加ClientPowerBoxSharedData添加新字段 isEnableSsl & 让PowerBoxWSClient继承了父类的#en/disableSSL方法
* 添加ClientPowerBoxSharedData添加新字段 isEnableSsl,用于WS地址协议头判断 * 让PowerBoxWSClient继承了父类的#enableSSL
#disableSSL方法以适配添加ClientPowerBoxSharedData添加新字段的字段 isEnableSsl
2025-09-21 22:20:32 +08:00
fefa14a202 feat(扩展字段): 修正 DGPBClientManager 的实现接口 & 在ClientPowerBoxSharedData添加新字段rqCodeUrl
* 修正 DGPBClientManager 的实现接口为com.r3944realms.dg_lab.api.manager.IDGLabManager *
在ClientPowerBoxSharedData添加新字段rqCodeUrl用于辅助访问二维码Url
2025-09-21 20:28:57 +08:00
67f4513817 feat(添加了ssl支持): 4.2.9.16 添加SSL支持
2025-09-21-1
2025-09-21 16:40:33 +08:00
c14d77400d build: 测试构建 v8 2025-09-21 15:46:31 +08:00
a966e7c2f5 build: 测试构建 v7 2025-09-21 15:39:59 +08:00
4b91763439 build: 测试构建 v6 2025-09-21 15:35:35 +08:00
f1278786f7 build: 测试构建 v5 2025-09-21 15:33:07 +08:00
3fb9f9b7cf build: 构建测试 v4 2025-09-21 15:30:42 +08:00
41 changed files with 1528 additions and 377 deletions

View File

@ -2,16 +2,16 @@ name: Build and Release
on:
push:
tags:
- 'build*' # 当推送以 build:开头的 tag 时触发,比如 buildXXXX
branches:
- "rebuild-develop" # develop 分支只构建
- "rebuild-release" # release 分支构建 + 发布
workflow_dispatch: # 允许手动触发
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository #在 GitHub Actions 的虚拟机上,把仓库里的代码拉下来
- name: Checkout repository
uses: actions/checkout@v3
- name: Set up JDK 17
@ -26,36 +26,54 @@ jobs:
- name: Build with Gradle
run: ./gradlew clean build
- name: Upload build artifacts
uses: actions/upload-artifact@v3
- name: Upload common jar
uses: actions/upload-artifact@v4
with:
name: my-build
path: '**/build/libs/*.jar'
name: Common
path: Common/build/libs/*.jar
- name: Upload common api jar
uses: actions/upload-artifact@v4
with:
name: CommonApi
path: CommonApi/build/libs/*.jar
release:
needs: build # 这个 job 依赖于上一个 job build 完成。
needs: build
runs-on: ubuntu-latest
steps:
- name: Download build artifact # 把上一个 job 上传的构建产物下载到当前 job 的 runner 上。
uses: actions/download-artifact@v3
with:
name: my-build
path: ./build-artifacts
- name: Create GitHub Release # 在 GitHub 上创建一个新的 Release版本发布
if: github.ref_name == 'rebuild-release' # 仅在 release 分支执行 release job
steps:
# 下载构建产物
- name: Download Common artifact
uses: actions/download-artifact@v4
with:
name: Common
path: ./build-artifacts/Common
- name: Download CommonApi artifact
uses: actions/download-artifact@v4
with:
name: CommonApi
path: ./build-artifacts/CommonApi
# 创建 GitHub Release
- name: Create GitHub Release
id: create_release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ github.ref_name }}
name: Release ${{ github.ref_name }}
body: |
自动发布所有子项目构建产物。
tag_name: "release-${{ github.run_number }}" # 可用 run_number 或自定义版本号
name: Release ${{ github.run_number }}
body: 自动发布所有子项目构建产物
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Upload artifact to Release # 上传构建产物到 Release
uses: softprops/action-gh-release@v1
with:
files: ./build-artifacts/**/*.jar
# 上传子项目 JAR
- name: Upload jars to Release
run: |
for file in ./build-artifacts/**/*.jar; do
echo "Uploading $file"
gh release upload "release-${GITHUB_RUN_NUMBER}" "$file" --repo "${GITHUB_REPOSITORY}" --clobber
done
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -0,0 +1,204 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaDocConfiguration">
<GENERAL>
<MODE>UPDATE</MODE>
<OVERRIDDEN_METHODS>false</OVERRIDDEN_METHODS>
<SPLITTED_CLASS_NAME>true</SPLITTED_CLASS_NAME>
<LEVELS>
<LEVEL>TYPE</LEVEL>
<LEVEL>METHOD</LEVEL>
<LEVEL>FIELD</LEVEL>
</LEVELS>
<VISIBILITIES>
<VISIBILITY>PUBLIC</VISIBILITY>
<VISIBILITY>DEFAULT</VISIBILITY>
<VISIBILITY>PROTECTED</VISIBILITY>
</VISIBILITIES>
</GENERAL>
<TEMPLATES>
<CLASSES>
<CLASS>
<KEY>^.*(public|protected|private)*.+interface\s+\w+.*</KEY>
<VALUE>/**\n
* The interface ${name}.\n
&lt;#if element.typeParameters?has_content&gt; * \n
&lt;/#if&gt;
&lt;#list element.typeParameters as typeParameter&gt;
* @param &lt;${typeParameter.name}&gt; the type parameter\n
&lt;/#list&gt;
*/</VALUE>
</CLASS>
<CLASS>
<KEY>^.*(public|protected|private)*.+enum\s+\w+.*</KEY>
<VALUE>/**\n
* The enum ${name}.\n
*/</VALUE>
</CLASS>
<CLASS>
<KEY>^.*(public|protected|private)*.+class\s+\w+.*</KEY>
<VALUE>/**\n
* The type ${name}.\n
&lt;#if element.typeParameters?has_content&gt; * \n
&lt;/#if&gt;
&lt;#list element.typeParameters as typeParameter&gt;
* @param &lt;${typeParameter.name}&gt; the type parameter\n
&lt;/#list&gt;
*/</VALUE>
</CLASS>
<CLASS>
<KEY>.+</KEY>
<VALUE>/**\n
* The type ${name}.\n
*/</VALUE>
</CLASS>
</CLASSES>
<CONSTRUCTORS>
<CONSTRUCTOR>
<KEY>.+</KEY>
<VALUE>/**\n
* Instantiates a new ${name}.\n
&lt;#if element.parameterList.parameters?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.parameterList.parameters as parameter&gt;
* @param ${parameter.name} the ${paramNames[parameter.name]}\n
&lt;/#list&gt;
&lt;#if element.throwsList.referenceElements?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.throwsList.referenceElements as exception&gt;
* @throws ${exception.referenceName} the ${exceptionNames[exception.referenceName]}\n
&lt;/#list&gt;
*/</VALUE>
</CONSTRUCTOR>
</CONSTRUCTORS>
<METHODS>
<METHOD>
<KEY>^.*(public|protected|private)*\s*.*(\w(\s*&lt;.+&gt;)*)+\s+get\w+\s*\(.*\).+</KEY>
<VALUE>/**\n
* Gets ${partName}.\n
&lt;#if element.typeParameters?has_content&gt; * \n
&lt;/#if&gt;
&lt;#list element.typeParameters as typeParameter&gt;
* @param &lt;${typeParameter.name}&gt; the type parameter\n
&lt;/#list&gt;
&lt;#if element.parameterList.parameters?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.parameterList.parameters as parameter&gt;
* @param ${parameter.name} the ${paramNames[parameter.name]}\n
&lt;/#list&gt;
&lt;#if isNotVoid&gt;
*\n
* @return the ${partName}\n
&lt;/#if&gt;
&lt;#if element.throwsList.referenceElements?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.throwsList.referenceElements as exception&gt;
* @throws ${exception.referenceName} the ${exceptionNames[exception.referenceName]}\n
&lt;/#list&gt;
*/</VALUE>
</METHOD>
<METHOD>
<KEY>^.*(public|protected|private)*\s*.*(void|\w(\s*&lt;.+&gt;)*)+\s+set\w+\s*\(.*\).+</KEY>
<VALUE>/**\n
* Sets ${partName}.\n
&lt;#if element.typeParameters?has_content&gt; * \n
&lt;/#if&gt;
&lt;#list element.typeParameters as typeParameter&gt;
* @param &lt;${typeParameter.name}&gt; the type parameter\n
&lt;/#list&gt;
&lt;#if element.parameterList.parameters?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.parameterList.parameters as parameter&gt;
* @param ${parameter.name} the ${paramNames[parameter.name]}\n
&lt;/#list&gt;
&lt;#if isNotVoid&gt;
*\n
* @return the ${partName}\n
&lt;/#if&gt;
&lt;#if element.throwsList.referenceElements?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.throwsList.referenceElements as exception&gt;
* @throws ${exception.referenceName} the ${exceptionNames[exception.referenceName]}\n
&lt;/#list&gt;
*/</VALUE>
</METHOD>
<METHOD>
<KEY>^.*((public\s+static)|(static\s+public))\s+void\s+main\s*\(\s*String\s*(\[\s*\]|\.\.\.)\s+\w+\s*\).+</KEY>
<VALUE>/**\n
* The entry point of application.\n
&lt;#if element.parameterList.parameters?has_content&gt;
*\n
&lt;/#if&gt;
* @param ${element.parameterList.parameters[0].name} the input arguments\n
&lt;#if element.throwsList.referenceElements?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.throwsList.referenceElements as exception&gt;
* @throws ${exception.referenceName} the ${exceptionNames[exception.referenceName]}\n
&lt;/#list&gt;
*/</VALUE>
</METHOD>
<METHOD>
<KEY>.+</KEY>
<VALUE>/**\n
* ${name}&lt;#if isNotVoid&gt; ${return}&lt;/#if&gt;.\n
&lt;#if element.typeParameters?has_content&gt; * \n
&lt;/#if&gt;
&lt;#list element.typeParameters as typeParameter&gt;
* @param &lt;${typeParameter.name}&gt; the type parameter\n
&lt;/#list&gt;
&lt;#if element.parameterList.parameters?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.parameterList.parameters as parameter&gt;
* @param ${parameter.name} the ${paramNames[parameter.name]}\n
&lt;/#list&gt;
&lt;#if isNotVoid&gt;
*\n
* @return the ${return}\n
&lt;/#if&gt;
&lt;#if element.throwsList.referenceElements?has_content&gt;
*\n
&lt;/#if&gt;
&lt;#list element.throwsList.referenceElements as exception&gt;
* @throws ${exception.referenceName} the ${exceptionNames[exception.referenceName]}\n
&lt;/#list&gt;
*/</VALUE>
</METHOD>
</METHODS>
<FIELDS>
<FIELD>
<KEY>^.*(public|protected|private)*.+static.*(\w\s\w)+.+</KEY>
<VALUE>/**\n
* The constant ${element.getName()}.\n
*/</VALUE>
</FIELD>
<FIELD>
<KEY>^.*(public|protected|private)*.*(\w\s\w)+.+</KEY>
<VALUE>/**\n
&lt;#if element.parent.isInterface()&gt;
* The constant ${element.getName()}.\n
&lt;#else&gt;
* The ${name}.\n
&lt;/#if&gt; */</VALUE>
</FIELD>
<FIELD>
<KEY>.+</KEY>
<VALUE>/**\n
&lt;#if element.parent.isEnum()&gt;
*${name} ${typeName}.\n
&lt;#else&gt;
* The ${name}.\n
&lt;/#if&gt;*/</VALUE>
</FIELD>
</FIELDS>
</TEMPLATES>
</component>
</project>

View File

@ -1,4 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ASMIdeaPluginConfiguration">
<asm skipDebug="false" skipFrames="false" skipCode="false" expandFrames="false" />

124
.idea/uiDesigner.xml Normal file
View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

View File

@ -21,33 +21,27 @@ base {
repositories {
mavenCentral()
}
javadoc {
options.encoding = 'UTF-8'
options.charSet = 'UTF-8'
//
options.addBooleanOption('Xdoclint:none', true)
options.addStringOption('Xmaxwarns', '10')
}
dependencies {
// Common CommonApi
api project(':CommonApi')
implementation 'org.apache.logging.log4j:log4j-core:2.23.1'
implementation 'org.apache.logging.log4j:log4j-api:2.23.1'
implementation 'org.apache.logging.log4j:log4j-slf4j2-impl:2.23.1'
implementation 'org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:1.7.0'
implementation 'org.apache.commons:commons-lang3:3.17.0'
implementation 'com.google.guava:guava:33.3.0-jre'
implementation 'io.netty:netty-all:4.1.109.Final'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.slf4j:slf4j-api:2.0.16'
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
// Sources JAR
task sourcesJar(type: Jar) {
tasks.register('sourcesJar', Jar) {
from sourceSets.main.allSource
archiveClassifier = 'sources'
}
// Javadoc JAR
task javadocJar(type: Jar) {
tasks.register('javadocJar', Jar) {
dependsOn javadoc
from javadoc.destinationDir
archiveClassifier = 'javadoc'
@ -82,9 +76,22 @@ publishing {
artifact shadowJar
artifact sourcesJar
artifact javadocJar
groupId = project.group.toString()
artifactId = base.archivesName.get()
version = project.version.toString()
pom {
name = "${project_name}"
description = "${project_name}"
url = "https://github.com/3944Realms/DG_LAB_DEVELOP"
licenses {
license {
name = 'Apache License 2.0'
url = 'https://www.apache.org/licenses/LICENSE-2.0.html'
}
}
issueManagement {
system = 'GitHub Issues'
url = 'https://github.com/3944Realms/DG_LAB_DEVELOP/issues'
}
}
}
}
}

View File

@ -16,9 +16,10 @@
package com.r3944realms.dg_lab.manager;
import com.r3944realms.dg_lab.api.manager.IDGLabManager;
import com.r3944realms.dg_lab.api.manager.Status;
import com.r3944realms.dg_lab.websocket.PowerBoxWSClient;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.websocket.PowerBoxWSClient;
import com.r3944realms.dg_lab.websocket.sharedData.ClientPowerBoxSharedData;
/**

View File

@ -18,8 +18,8 @@ package com.r3944realms.dg_lab.manager;
import com.r3944realms.dg_lab.api.manager.IDGLabManager;
import com.r3944realms.dg_lab.api.manager.Status;
import com.r3944realms.dg_lab.websocket.PowerBoxWSServer;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.websocket.PowerBoxWSServer;
import com.r3944realms.dg_lab.websocket.sharedData.ServerPowerBoxSharedData;
/**

View File

@ -17,11 +17,11 @@
package com.r3944realms.dg_lab.utils.timeTask;
import com.r3944realms.dg_lab.utils.annoation.NeedCompletedInFuture;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.api.websocket.message.PowerBoxMessage;
import com.r3944realms.dg_lab.api.websocket.message.role.PlaceholderRole;
import com.r3944realms.dg_lab.api.websocket.message.role.WebSocketClientRole;
import com.r3944realms.dg_lab.utils.annoation.NeedCompletedInFuture;
import io.netty.channel.ChannelHandlerContext;
import java.util.TimerTask;

View File

@ -18,9 +18,9 @@ package com.r3944realms.dg_lab.websocket;
import com.r3944realms.dg_lab.DgLab;
import com.r3944realms.dg_lab.api.manager.Status;
import com.r3944realms.dg_lab.api.websocket.IWebsocketClient;
import com.r3944realms.dg_lab.utils.stringUtils.StringHandlerUtil;
import com.r3944realms.dg_lab.utils.stringUtils.UrlValidator;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
@ -32,9 +32,14 @@ import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import java.io.File;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
@ -43,7 +48,7 @@ import java.util.concurrent.CompletableFuture;
/**
* 主要是处理netty逻辑以建立客户端
*/
public abstract class AbstractWebSocketClient {
public abstract class AbstractWebSocketClient implements IWebsocketClient {
/**
* 日志
*/
@ -51,29 +56,61 @@ public abstract class AbstractWebSocketClient {
/**
* 地址
*/
protected volatile String Address;
protected volatile String address;
/**
* 端口
*/
protected volatile int Port;
protected volatile int port;
/**
* 启用 SSL
*/
public void enableSSL() {
enableSSL(null);
}
/**
* 启用 SSL
* @param certFile 可选证书文件
*/
public void enableSSL(@Nullable File certFile) {
this.sslEnabled = true;
this.certFile = certFile;
}
/**
* 禁用SSL
*/
public void disableSSL() {
this.sslEnabled = false;
}
/**
* 是否启用 SSL
*/
boolean sslEnabled;
/**
* 客户端可选信任证书
*/
File certFile;
/**
* 客户端启动类
*/
private Bootstrap ClientBootstrap;
private Bootstrap clientBootstrap;
/**
* 客户端事件线程组
*/
private EventLoopGroup ClientEventLoopGroup;
private EventLoopGroup clientEventLoopGroup;
/**
* The Client channel.
*/
protected Channel ClientChannel;
protected Channel clientChannel;
private Thread WebSocketClientThread;
private Thread webSocketClientThread;
/**
* The Client status.
*/
protected volatile Status ClientStatus = Status.WAITING_FOR_INIT;
protected volatile Status clientStatus = Status.WAITING_FOR_INIT;
/**
* Gets status.
@ -81,7 +118,17 @@ public abstract class AbstractWebSocketClient {
* @return the status
*/
public Status getStatus() {
return this.ClientStatus;
return this.clientStatus;
}
/**
* 是否启用 SSL
*
* @return enable
*/
@Override
public boolean isSSLEnabled() {
return sslEnabled;
}
/**
@ -90,7 +137,7 @@ public abstract class AbstractWebSocketClient {
* @param status the status
*/
public void setStatus(Status status) {
this.ClientStatus = status;
this.clientStatus = status;
}
/**
@ -98,8 +145,8 @@ public abstract class AbstractWebSocketClient {
*/
protected AbstractWebSocketClient() {
try {
this.Address = InetAddress.getLocalHost().getHostAddress();
this.Port = 9000;
this.address = InetAddress.getLocalHost().getHostAddress();
this.port = 9000;
} catch (UnknownHostException e) {
logger.error(e.getMessage());
}
@ -113,8 +160,8 @@ public abstract class AbstractWebSocketClient {
protected AbstractWebSocketClient(int port) {
try {
InetAddress localHost = InetAddress.getLocalHost();
this.Address = localHost.getHostAddress();
this.Port = UrlValidator.isValidPort(port) ? port : 9000;
this.address = localHost.getHostAddress();
this.port = UrlValidator.isValidPort(port) ? port : 9000;
} catch (UnknownHostException e) {
logger.error(e.getMessage());
}
@ -128,24 +175,35 @@ public abstract class AbstractWebSocketClient {
*/
protected AbstractWebSocketClient(String address, int port) {
try {
this.Address = UrlValidator.isValidAddress(address) ? address : InetAddress.getLocalHost().getHostAddress();
this.Port = UrlValidator.isValidPort(port) ? port : 9000;
this.address = UrlValidator.isValidAddress(address) ? address : InetAddress.getLocalHost().getHostAddress();
this.port = UrlValidator.isValidPort(port) ? port : 9000;
} catch (UnknownHostException e) {
logger.error(e.getMessage());
}
}
@Override
public int getPort() {
return port;
}
/**
* Sets port.
*
* @param port the port
*/
@Override
public void setPort(int port) {
if (this.ClientStatus != Status.WAITING_FOR_INIT && this.ClientStatus != Status.STOPPED) {
if (this.clientStatus != Status.WAITING_FOR_INIT && this.clientStatus != Status.STOPPED) {
logger.error("Unable to change port to {}", port);
return;
}
this.Port = UrlValidator.isValidPort(port) ? port : 9000;
this.port = UrlValidator.isValidPort(port) ? port : 9000;
}
@Override
public String getAddress() {
return address;
}
/**
@ -154,12 +212,12 @@ public abstract class AbstractWebSocketClient {
* @param address the address
*/
public void setAddress(String address) {
if (this.ClientStatus != Status.WAITING_FOR_INIT && this.ClientStatus != Status.STOPPED) {
if (this.clientStatus != Status.WAITING_FOR_INIT && this.clientStatus != Status.STOPPED) {
logger.error("Unable to change address to {}", address);
return;
}
try {
this.Address = UrlValidator.isValidAddress(address) ? address : InetAddress.getLocalHost().getHostAddress();
this.address = UrlValidator.isValidAddress(address) ? address : InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
@ -186,7 +244,7 @@ public abstract class AbstractWebSocketClient {
* @return the url
*/
public String getUrl() {
return StringHandlerUtil.buildWebSocketURL(Address, Port, false);
return StringHandlerUtil.buildWebSocketURL(address, port, false);
}
/**
@ -205,22 +263,36 @@ public abstract class AbstractWebSocketClient {
* Init thread.
*/
protected final void initThread() {
ClientEventLoopGroup = new NioEventLoopGroup();
WebSocketClientThread = new Thread(() -> {
ClientStatus = Status.STARTING;
ClientBootstrap = new Bootstrap();
ClientBootstrap.group(ClientEventLoopGroup);
ClientBootstrap.channel(NioSocketChannel.class);
ClientBootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
init();
clientEventLoopGroup = new NioEventLoopGroup();
webSocketClientThread = new Thread(() -> {
clientStatus = Status.STARTING;
clientBootstrap = new Bootstrap();
clientBootstrap.group(clientEventLoopGroup);
clientBootstrap.channel(NioSocketChannel.class);
clientBootstrap.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
protected void initChannel(NioSocketChannel ch) throws SSLException {
ChannelPipeline pipeline = ch.pipeline();
// SSL 支持
if (sslEnabled) {
SslContext sslCtx;
if (certFile != null && certFile.exists()) {
sslCtx = SslContextBuilder.forClient()
.trustManager(certFile)
.build();
} else {
// 默认信任所有受信任的 CA
sslCtx = SslContextBuilder.forClient().build();
}
pipeline.addFirst(sslCtx.newHandler(ch.alloc(), address, port));
}
pipeline.addLast(DgLab.LOGGING_HANDLER,
new HttpClientCodec(),
new HttpObjectAggregator(65536),
new WebSocketClientProtocolHandler(
WebSocketClientHandshakerFactory.newHandshaker(
URI.create(StringHandlerUtil.buildWebSocketURL(Address, Port, false)),
URI.create(StringHandlerUtil.buildWebSocketURL(address, port, false)),
WebSocketVersion.V13,
null,
false,
@ -232,17 +304,17 @@ public abstract class AbstractWebSocketClient {
}
});
try {
ChannelFuture channelFuture = ClientBootstrap.connect(Address, Port);
ClientStatus = Status.RUNNING;
started();
ClientChannel = channelFuture.sync().channel();
ClientChannel.closeFuture().sync();
ChannelFuture channelFuture = clientBootstrap.connect(address, port);
clientStatus = Status.RUNNING;
onStarted();
clientChannel = channelFuture.sync().channel();
clientChannel.closeFuture().sync();
} catch (Exception e) {
startingError();
ClientStatus = Status.ERROR;
onStartingError("Catch Exception: " + e.getMessage());
clientStatus = Status.ERROR;
logger.error(e.getMessage());
} finally {
if(ClientStatus == Status.ERROR || ClientStatus == Status.RUNNING) stop();
if(clientStatus == Status.ERROR || clientStatus == Status.RUNNING) stop();
}
}, "WebSocketClient");
@ -258,23 +330,23 @@ public abstract class AbstractWebSocketClient {
* Start.
*/
public final void start() {
starting();
switch (ClientStatus) {
onStarting();
switch (clientStatus) {
case STARTING -> {
startingError();
logger.info("Client is already starting.");
onStartingError("Client is already onStarting");
logger.info("Client is already onStarting.");
}
case RUNNING -> {
startingError();
onStartingError("Client is already running.");
logger.info("Client is already running.");
}
case STOPPING -> {
startingError();
logger.info("Client is stopping");
onStartingError("Client is onStopping");
logger.info("Client is onStopping");
}
case STOPPED, WAITING_FOR_INIT -> {
initThread();
WebSocketClientThread.start();
webSocketClientThread.start();
start0();
}
}
@ -289,96 +361,58 @@ public abstract class AbstractWebSocketClient {
return CompletableFuture.runAsync(() -> {});
}
/**
* Starting.
*/
protected abstract void starting();
/**
* Starting error.
*/
protected abstract void startingError();
/**
* Started.
*/
protected abstract void started();
/**
* Stopping.
*/
protected abstract void stopping();
/**
* Stopping error.
*/
protected abstract void stoppingError();
/**
* Stopped.
*/
protected abstract void stopped();
/**
* Stop.
*/
public final void stop() {
stopping();
switch (ClientStatus) {
case WAITING_FOR_INIT -> {
stoppingError();
logger.warn("Not Init. (It shouldn't be happened)");
}
onStopping();
switch (clientStatus) {
case STARTING -> {
stoppingError();
logger.info("Client is starting, please waiting.");
onStoppingError("Client is already onStarting.");
logger.info("Client is onStarting, please waiting.");
}
case RUNNING, ERROR -> {
ClientStatus = Status.STOPPING;
clientStatus = Status.STOPPING;
CompletableFuture<Void> CliChanClose = CompletableFuture.runAsync(() -> {
if (ClientChannel != null && ClientChannel.isOpen()) {
if (clientChannel != null && clientChannel.isOpen()) {
try {
ClientChannel.close().sync();
clientChannel.close().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage());
} finally {
ClientChannel = null;
clientChannel = null;
}
}
});
CompletableFuture<Void> CliEvenClose = CliChanClose.thenRunAsync(() -> {
if (ClientEventLoopGroup != null) {
if (clientEventLoopGroup != null) {
try {
ClientEventLoopGroup.shutdownGracefully().sync();
clientEventLoopGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage());
} finally {
ClientEventLoopGroup = null;
clientEventLoopGroup = null;
}
}
});
CliEvenClose.thenCombineAsync(stop0(), (a, b) -> {
ClientStatus = Status.STOPPED;
ClientBootstrap = null;
stopped();
clientStatus = Status.STOPPED;
clientBootstrap = null;
onStopped();
return null;
});
}
case STOPPING -> {
stoppingError();
logger.info("Client is already stopping");
onStoppingError("Client is already onStopping.");
logger.info("Client is already onStopping");
}
case STOPPED -> {
stoppingError();
logger.info("Client has stopped");
case STOPPED, WAITING_FOR_INIT -> {
onStoppingError("Client has been onStopped.");
logger.info("Client has onStopped");
}
}
}
/**
* 向所连接的服务器发送消息
*
* @param message 消息
*/
public abstract void send(Message message);
}

View File

@ -19,9 +19,10 @@ package com.r3944realms.dg_lab.websocket;
import com.r3944realms.dg_lab.DgLab;
import com.r3944realms.dg_lab.api.manager.Status;
import com.r3944realms.dg_lab.api.websocket.IWebSocketServer;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.utils.stringUtils.UrlValidator;
import com.r3944realms.dg_lab.websocket.handler.server.HttpRequestHandler;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
@ -31,55 +32,81 @@ import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import java.io.File;
import java.util.concurrent.CompletableFuture;
/**
* 主要是处理netty逻辑以建立服务端
*/
@SuppressWarnings({"DuplicatedCode", "LoggingSimilarMessage"})
public abstract class AbstractWebSocketServer {
public abstract class AbstractWebSocketServer implements IWebSocketServer {
/**
* The constant logger.
*/
protected static final Logger logger = LoggerFactory.getLogger(AbstractWebSocketServer.class);
private int Port;
/**
* Should enable SSL
*/
boolean sslEnabled;
/**
* SSL 密码
*/
String sslPassword;
/**
* 证书文件
*/
File certFile;
/**
* 私钥文件
*/
File keyFile;
private String listenAddress;
private int port;
/**
* The Server bootstrap.
*/
protected ServerBootstrap ServerBootstrap;
protected ServerBootstrap serverBootstrap;
/**
* The Boss group.
*/
protected EventLoopGroup BossGroup,
protected EventLoopGroup bossGroup,
/**
* The Worker group.
*/
WorkerGroup;
workerGroup;
/**
* The Server channel.
*/
protected Channel ServerChannel;
protected Channel serverChannel;
/**
* The Websocket server thread.
*/
protected Thread WebsocketServerThread;
protected Thread websocketServerThread;
/**
* The Server status.
*/
protected volatile Status ServerStatus = Status.WAITING_FOR_INIT;
protected volatile Status serverStatus = Status.WAITING_FOR_INIT;
/**
* Instantiates a new Abstract web socket server.
*/
protected AbstractWebSocketServer() {
Port = 9000;
port = 9000;
}
/**
@ -88,47 +115,61 @@ public abstract class AbstractWebSocketServer {
* @param port the port
*/
protected AbstractWebSocketServer(int port) {
Port = port;
this.port = port;
}
@Override
public void setListenedAddress(String address) {
this.listenAddress = address;
}
@Override
public String getListenedAddress() {
return listenAddress == null ? "0.0.0.0" : listenAddress;
}
/**
* Gets status.
*
* @return the status
*/
public Status getStatus() {
return this.ServerStatus;
return this.serverStatus;
}
/**
* Sets status.
*
* @param status the status
*/
public void setStatus(Status status) {
this.ServerStatus = status;
this.serverStatus = status;
}
/**
* Sets port.
*
* @param port the port
*/
public void setPort(int port) {
if(this.ServerStatus != Status.WAITING_FOR_INIT && this.ServerStatus != Status.STOPPED) {
if(this.serverStatus != Status.WAITING_FOR_INIT && this.serverStatus != Status.STOPPED) {
logger.error("Unable to Change Port to {}", port);
return;
}
this.Port = UrlValidator.isValidPort(port) ? port : 9000;
this.port = UrlValidator.isValidPort(port) ? port : 9000;
}
/**
* Gets port.
*
* @return the port
*/
public int getPort() {
return Port;
return port;
}
public boolean isSSLEnabled() {
return sslEnabled;
}
public void enableSSL(@NotNull File certFile, @NotNull File keyFile) {
enableSSL(certFile, keyFile, null);
}
public void enableSSL(@NotNull File certFile, @NotNull File keyFile, @Nullable String password) {
this.sslEnabled = true;
this.certFile = certFile;
this.keyFile = keyFile;
this.sslPassword = password;
}
public void disableSSL() {
this.sslEnabled = false;
}
/**
@ -147,20 +188,26 @@ public abstract class AbstractWebSocketServer {
* Init thread.
*/
protected final void initThread() {
BossGroup = new NioEventLoopGroup();
WorkerGroup = new NioEventLoopGroup();
WebsocketServerThread = new Thread(() ->{
init();
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
websocketServerThread = new Thread(() ->{
try {
ServerBootstrap = new ServerBootstrap();
ServerStatus = Status.STARTING;
ServerBootstrap.option(ChannelOption.SO_BACKLOG, 1024)
serverBootstrap = new ServerBootstrap();
serverStatus = Status.STARTING;
serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ServerBootstrap.group(BossGroup, WorkerGroup);
ServerBootstrap.channel(NioServerSocketChannel.class);
ServerBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
serverBootstrap.group(bossGroup, workerGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
protected void initChannel(NioSocketChannel ch) throws SSLException {
ChannelPipeline pipeline = ch.pipeline();
// 根据配置启用 SSL
if (sslEnabled) {
SslContext sslCtx = SslContextBuilder.forServer(certFile, keyFile, sslPassword).build();
pipeline.addFirst(sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast(DgLab.LOGGING_HANDLER);
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
@ -171,55 +218,25 @@ public abstract class AbstractWebSocketServer {
}
});
logger.debug("WebSocketServer try binding port ... ");
ChannelFuture channelFuture = ServerBootstrap.bind("0.0.0.0",Port);
ChannelFuture channelFuture = serverBootstrap.bind(getListenedAddress(), port);
channelFuture.sync();
ServerChannel = channelFuture.channel();
ServerStatus = Status.RUNNING;
started();
logger.info("WebSocketServer start on the port of {}", Port);
logger.debug("WebSocketServer listening on port {}", Port);
serverChannel = channelFuture.channel();
serverStatus = Status.RUNNING;
onStarted();
logger.info("WebSocketServer start on the port of {}{}", port, sslEnabled ? " (SSL)" : "");
logger.debug("WebSocketServer listening on port {}", port);
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
ServerStatus = Status.ERROR;
stoppingError();
serverStatus = Status.ERROR;
onStoppingError("Catch Exception:" + e.getMessage());
logger.error(e.getMessage());
} finally {
if(ServerStatus == Status.ERROR || ServerStatus == Status.RUNNING) stop();
if(serverStatus == Status.ERROR || serverStatus == Status.RUNNING) stop();
}
}, "WebSocketServer");
initThread0();
}
/**
* Starting.
*/
protected abstract void starting();
/**
* Starting error.
*/
protected abstract void startingError();
/**
* Started.
*/
protected abstract void started();
/**
* Stopping.
*/
protected abstract void stopping();
/**
* Stopping error.
*/
protected abstract void stoppingError();
/**
* Stopped.
*/
protected abstract void stopped();
/**
* 自定义Start后续逻辑
*/
@ -231,23 +248,23 @@ public abstract class AbstractWebSocketServer {
* Start.
*/
public final void start() {
starting();
switch (ServerStatus) {
onStarting();
switch (serverStatus) {
case STARTING -> {
startingError();
logger.info("Server is already starting.");
onStartingError("Server is already onStarting.");
logger.info("Server is already onStarting.");
}
case RUNNING -> {
startingError();
onStartingError("Server is already running.");
logger.info("Server is already running.");
}
case STOPPING -> {
startingError();
logger.info("Server is stopping");
onStartingError("Server is onStopping");
logger.info("Server is onStopping");
}
case STOPPED, WAITING_FOR_INIT -> {
initThread();
WebsocketServerThread.start();
websocketServerThread.start();
start0();
}
}
@ -266,80 +283,68 @@ public abstract class AbstractWebSocketServer {
* Stop.
*/
public final void stop() {
stopping();
switch (ServerStatus) {
case WAITING_FOR_INIT -> {
stoppingError();
logger.warn("Not Init. (It shouldn't be happened)");
}
onStopping();
switch (serverStatus) {
case STARTING -> {
stoppingError();
logger.info("Server is starting, please waiting.");
onStoppingError("Server is onStarting, please waiting.");
logger.info("Server is onStarting, please waiting.");
}
case RUNNING -> {
ServerStatus = Status.STOPPING;
serverStatus = Status.STOPPING;
// Close the server channel if it's open
CompletableFuture<Void> SerChanClose = CompletableFuture.runAsync(() -> {
if (ServerChannel != null && ServerChannel.isOpen()) {
if (serverChannel != null && serverChannel.isOpen()) {
try {
ServerChannel.close().sync();
serverChannel.close().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage());
} finally {
ServerChannel = null;
serverChannel = null;
}
}
});
// Shutdown the event loop groups
CompletableFuture<Void> BosGroClose = SerChanClose.thenRunAsync(() -> {
if (BossGroup != null) {
if (bossGroup != null) {
try {
BossGroup.shutdownGracefully().sync();
bossGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage());
} finally {
BossGroup = null;
bossGroup = null;
}
}
}
);
CompletableFuture<Void> WorGroClose = SerChanClose.thenRunAsync(() -> {
if (WorkerGroup != null) {
if (workerGroup != null) {
try {
WorkerGroup.shutdownGracefully().sync();
workerGroup.shutdownGracefully().sync();
} catch (InterruptedException e) {
logger.error(e.getMessage());
} finally {
WorkerGroup = null;
workerGroup = null;
}
}
});
BosGroClose.thenCombineAsync(WorGroClose, (a,b) -> {
stop0().thenRunAsync(() -> {
ServerStatus = Status.STOPPED;
ServerBootstrap = null;
stopped();
serverStatus = Status.STOPPED;
serverBootstrap = null;
onStopped();
});
return null;
});
}
case STOPPING -> {
stoppingError();
logger.info("Server is already stopping");
onStoppingError("Server is already onStopping");
logger.info("Server is already onStopping");
}
case STOPPED -> {
stoppingError();
logger.info("Server has stopped");
onStoppingError("Server has onStopped");
logger.info("Server has onStopped");
}
}
}
/**
* 向指定的客户端发送消息
*
* @param clientId 客户端UUID
* @param message 消息
*/
public abstract void send(String clientId, Message message);
}

View File

@ -17,12 +17,12 @@
package com.r3944realms.dg_lab.websocket;
import com.r3944realms.dg_lab.api.operation.ClientOperation;
import com.r3944realms.dg_lab.websocket.handler.client.ClientDLPBHandler;
import com.r3944realms.dg_lab.websocket.handler.client.ClientDLPBHandlerContextWrapper;
import com.r3944realms.dg_lab.websocket.handler.client.DefaultClientOperation;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.api.websocket.message.PowerBoxMessage;
import com.r3944realms.dg_lab.api.websocket.message.role.WebSocketClientRole;
import com.r3944realms.dg_lab.websocket.handler.client.ClientDLPBHandler;
import com.r3944realms.dg_lab.websocket.handler.client.ClientDLPBHandlerContextWrapper;
import com.r3944realms.dg_lab.websocket.handler.client.DefaultClientOperation;
import com.r3944realms.dg_lab.websocket.sharedData.ClientPowerBoxSharedData;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
@ -62,8 +62,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData;
this.operation = operation;
this.role = role;
sharedData.address = this.Address;
sharedData.port = this.Port;
sharedData.address = this.address;
sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, false);
}
@ -82,8 +82,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData;
this.operation = operation;
this.role = role;
sharedData.address = this.Address;
sharedData.port = this.Port;
sharedData.address = this.address;
sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, false);
}
@ -123,8 +123,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData;
this.operation = operation;
this.role = role;
sharedData.address = this.Address;
sharedData.port = this.Port;
sharedData.address = this.address;
sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, useRoleMsgMode);
}
@ -144,8 +144,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData;
this.operation = operation;
this.role = role;
sharedData.address = this.Address;
sharedData.port = this.Port;
sharedData.address = this.address;
sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, useRoleMsgMode);
}
@ -178,39 +178,59 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
}
@Override
protected void starting() {
public void init() {
}
@Override
public void onStarting() {
operation.ClientStartingHandler();
}
@Override
protected void startingError() {
operation.ClientStartingErrorHandler();
public void onStartingError(String msg) {
operation.ClientStartingErrorHandler(msg);
}
@Override
protected void started() {
public void onStarted() {
operation.ClientStartedHandler();
}
@Override
protected void stopping() {
public void onStopping() {
operation.ClientStoppingHandler();
}
@Override
protected void stoppingError() {
operation.ClientStoppingErrorHandler();
public void onStoppingError(String msg) {
operation.ClientStoppingErrorHandler(msg);
}
@Override
protected void stopped() {
public void onStopped() {
operation.ClientStoppedHandler();
}
@Override
public void enableSSL() {
super.enableSSL();
sharedData.isEnableSsl = true;
}
@Override
public void disableSSL() {
super.disableSSL();
sharedData.isEnableSsl = false;
}
@Override
public void send(Message message) {
if(message instanceof PowerBoxMessage PBMessage) {
this.ClientChannel.writeAndFlush(new TextWebSocketFrame(PBMessage.getMsgJson()));
this.clientChannel.writeAndFlush(new TextWebSocketFrame(PBMessage.getMsgJson()));
} else {
logger.error("Message is not a PowerBoxMessage");
}

View File

@ -17,12 +17,13 @@
package com.r3944realms.dg_lab.websocket;
import com.r3944realms.dg_lab.api.operation.ServerOperation;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.api.websocket.message.PowerBoxMessage;
import com.r3944realms.dg_lab.api.websocket.message.data.type.PowerBoxDataType;
import com.r3944realms.dg_lab.api.websocket.message.role.WebSocketServerRole;
import com.r3944realms.dg_lab.websocket.handler.server.DefaultServerOperation;
import com.r3944realms.dg_lab.websocket.handler.server.ServerDLPBHandler;
import com.r3944realms.dg_lab.websocket.handler.server.ServerDLPBHandlerContextWrapper;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.api.websocket.message.PowerBoxMessage;
import com.r3944realms.dg_lab.api.websocket.message.role.WebSocketServerRole;
import com.r3944realms.dg_lab.websocket.sharedData.ServerPowerBoxSharedData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
@ -38,7 +39,7 @@ public class PowerBoxWSServer extends AbstractWebSocketServer {
/**
* The Shared data.
*/
protected final ServerPowerBoxSharedData SharedData;
protected final ServerPowerBoxSharedData sharedData;
/**
* The Role.
*/
@ -57,7 +58,7 @@ public class PowerBoxWSServer extends AbstractWebSocketServer {
* @param operation the operation
*/
public PowerBoxWSServer(ServerPowerBoxSharedData sharedData, WebSocketServerRole role, ServerOperation operation) {
this.SharedData = sharedData;
this.sharedData = sharedData;
this.role = role;
this.operation = operation;
contextWrapper = new ServerDLPBHandlerContextWrapper(
@ -77,7 +78,7 @@ public class PowerBoxWSServer extends AbstractWebSocketServer {
*/
public PowerBoxWSServer(ServerPowerBoxSharedData sharedData, WebSocketServerRole role, ServerOperation operation, int port) {
super(port);
this.SharedData = sharedData;
this.sharedData = sharedData;
this.role = role;
this.operation = operation;
contextWrapper = new ServerDLPBHandlerContextWrapper(
@ -114,51 +115,63 @@ public class PowerBoxWSServer extends AbstractWebSocketServer {
}
@Override
protected void starting() {
public void init() {
}
@Override
public void onStarting() {
operation.ServerStartingHandler();
}
@Override
protected void startingError() {
operation.ServerStartingErrorHandler();
public void onStartingError(String error) {
operation.ServerStartingErrorHandler(error);
}
@Override
protected void started() {
public void onStarted() {
operation.ServerStartedHandler();
}
@Override
protected void stopping() {
public void onStopping() {
operation.ServerStoppingHandler();
}
@Override
protected void stoppingError() {
operation.ServerStoppingErrorHandler();
public void onStoppingError(String error) {
operation.ServerStoppingErrorHandler(error);
}
@Override
protected void stopped() {
public void onStopped() {
operation.ServerStoppedHandler();
}
@Override
public void send(String connectId, Message message) {
if(message instanceof PowerBoxMessage PBMessage) {
ChannelHandlerContext context = SharedData.connections.get(connectId);//获取连接连接的Context
ChannelHandlerContext context = sharedData.connections.get(connectId);//获取连接连接的Context
if(context != null) {
String targetId = SharedData.relations.get(connectId);
if(targetId.isEmpty()) { //该上下文为客户端
context.writeAndFlush(new TextWebSocketFrame(PBMessage.getMsgJson()));//发送给客户端
ChannelHandlerContext appContext = SharedData.connections.get(targetId);
appContext.writeAndFlush(new TextWebSocketFrame(PBMessage.getDataJson()));//发送给APP端
} else if(SharedData.relations.containsValue(targetId)){ // 绑定状态的APP端
//仅对APP发信息
context.writeAndFlush(new TextWebSocketFrame(PBMessage.getDataJson()));
String targetId = sharedData.relations.get(connectId);
if(targetId != null) {
if (targetId.isEmpty()) { //该上下文为客户端
context.writeAndFlush(new TextWebSocketFrame(PBMessage.getMsgJson()));//发送给客户端
ChannelHandlerContext appContext = sharedData.connections.get(targetId);
appContext.writeAndFlush(new TextWebSocketFrame(PBMessage.getDataJson()));//发送给APP端
} else if(sharedData.relations.containsValue(targetId)){ // 绑定状态的APP端
//仅对APP发信息
context.writeAndFlush(new TextWebSocketFrame(PBMessage.getDataJson()));
} else { // 未绑定状态不可发送消息
logger.error("Can't send Msg to no relationship obj.");
}
} else if (PBMessage.commandType == PowerBoxDataType._NC_BIND_) {
//客户端写入绑定消息
context.writeAndFlush(new TextWebSocketFrame(PBMessage.getMsgJson()));
} else { // 未绑定状态不可发送消息
logger.error("Can't send Msg to no relationship obj.");
logger.error("Can't send Non-Binding Msg to no relationship obj.");
}
} else {
logger.error("Find that Target is invalid.");
@ -174,7 +187,7 @@ public class PowerBoxWSServer extends AbstractWebSocketServer {
* @return the shared data
*/
public ServerPowerBoxSharedData getSharedData() {
return SharedData;
return sharedData;
}
@Override

View File

@ -16,9 +16,9 @@
package com.r3944realms.dg_lab.websocket.handler.client;
import com.r3944realms.dg_lab.api.websocket.sharedData.ISharedData;
import com.r3944realms.dg_lab.websocket.handler.AbstractDgLabPowerBoxHandler;
import com.r3944realms.dg_lab.websocket.handler.IAttachSharedData;
import com.r3944realms.dg_lab.api.websocket.sharedData.ISharedData;
import io.netty.channel.ChannelHandler;
/**

View File

@ -18,15 +18,15 @@ package com.r3944realms.dg_lab.websocket.handler.client;
import com.r3944realms.dg_lab.api.operation.ClientOperation;
import com.r3944realms.dg_lab.api.operation.IOperation;
import com.r3944realms.dg_lab.websocket.handler.AbstractDgLabPowerBoxHandlerContextWrapper;
import com.r3944realms.dg_lab.api.websocket.message.PowerBoxMessage;
import com.r3944realms.dg_lab.api.websocket.message.data.PowerBoxData;
import com.r3944realms.dg_lab.api.websocket.message.role.Role;
import com.r3944realms.dg_lab.api.websocket.message.role.WebSocketClientRole;
import com.r3944realms.dg_lab.api.websocket.message.role.WebSocketServerRole;
import com.r3944realms.dg_lab.api.websocket.message.role.type.RoleType;
import com.r3944realms.dg_lab.websocket.sharedData.ClientPowerBoxSharedData;
import com.r3944realms.dg_lab.api.websocket.sharedData.ISharedData;
import com.r3944realms.dg_lab.websocket.handler.AbstractDgLabPowerBoxHandlerContextWrapper;
import com.r3944realms.dg_lab.websocket.sharedData.ClientPowerBoxSharedData;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
@ -115,7 +115,7 @@ public class ClientDLPBHandlerContextWrapper extends AbstractDgLabPowerBoxHandle
//通过构造开启且如果有目标即连上了APP端则开启Message对象校验只有通过校验才能进读取data()
dataMsg = PowerBoxMessage.getNullMessage().getMessage(json);
//发送对象必须是服务器类型 接收者本客户端为占位对象类型 本客户端对象名字类型相同这里取反只有满足条件才能进入 else读取 data
if(
if (
dataMsg.direction.sender().type != RoleType.T_SERVER
&&
!(
@ -145,6 +145,7 @@ public class ClientDLPBHandlerContextWrapper extends AbstractDgLabPowerBoxHandle
((ClientPowerBoxSharedData)sharedData).connectionId = data.getClientId();
logger.info("收到clientId: {}", ConnectionId());
String qrCodeContext = "https://www.dungeon-lab.com/app-download.php#DGLAB-SOCKET#" + ((ClientPowerBoxSharedData)sharedData).getUrl() + ConnectionId();
((ClientPowerBoxSharedData) sharedData).rqCodeUrl = qrCodeContext;
TryCatch(i -> ((ClientOperation)operation).QrCodeUrlHandler(qrCodeContext));
TryCatch(i -> ((ClientOperation)operation).ShowQrCodeHandler());
logger.debug("重新生成QrCodeContext: {}",qrCodeContext);

View File

@ -34,8 +34,8 @@ public class DefaultClientOperation implements ClientOperation {
}
@Override
public void ClientStartingErrorHandler() {
//NOOP
public void ClientStartingErrorHandler(String errorMsg) {
}
@Override
@ -43,11 +43,13 @@ public class DefaultClientOperation implements ClientOperation {
//NOOP
}
@Override
public void ClientStoppingErrorHandler() {
public void ClientStoppingErrorHandler(String errorMsg) {
//NOOP
}
@Override
public void ClientStoppedHandler() {
//NOOP

View File

@ -74,8 +74,8 @@ public class DefaultServerOperation implements ServerOperation {
}
@Override
public void ServerStartingErrorHandler() {
public void ServerStartingErrorHandler(String errorMessage) {
//NOOP
}
@Override
@ -89,8 +89,8 @@ public class DefaultServerOperation implements ServerOperation {
}
@Override
public void ServerStoppingErrorHandler() {
public void ServerStoppingErrorHandler(String errorMessage) {
//NOOP
}
@Override
@ -98,6 +98,11 @@ public class DefaultServerOperation implements ServerOperation {
//NOOP
}
@Override
public void ClientSessionBuildInHandler(String clientId) {
//NOOP
}
@Override
public void InactiveConnectionRemoveHandler(String clientId) {
//NOOP

View File

@ -16,10 +16,10 @@
package com.r3944realms.dg_lab.websocket.handler.server;
import com.r3944realms.dg_lab.api.websocket.sharedData.ISharedData;
import com.r3944realms.dg_lab.websocket.handler.AbstractDgLabPowerBoxHandler;
import com.r3944realms.dg_lab.websocket.handler.AbstractDgLabPowerBoxHandlerContextWrapper;
import com.r3944realms.dg_lab.websocket.handler.IAttachSharedData;
import com.r3944realms.dg_lab.api.websocket.sharedData.ISharedData;
import io.netty.channel.ChannelHandler;

View File

@ -18,17 +18,17 @@ package com.r3944realms.dg_lab.websocket.handler.server;
import com.google.gson.JsonSyntaxException;
import com.r3944realms.dg_lab.api.operation.ServerOperation;
import com.r3944realms.dg_lab.api.websocket.message.role.*;
import com.r3944realms.dg_lab.utils.stringUtils.StringHandlerUtil;
import com.r3944realms.dg_lab.utils.timeTask.DgLabTimerTask;
import com.r3944realms.dg_lab.websocket.handler.AbstractDgLabPowerBoxHandlerContextWrapper;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import com.r3944realms.dg_lab.api.websocket.message.PowerBoxMessage;
import com.r3944realms.dg_lab.api.websocket.message.data.PowerBoxData;
import com.r3944realms.dg_lab.api.websocket.message.data.PowerBoxDataWithSingleAttachment;
import com.r3944realms.dg_lab.api.websocket.message.data.type.PowerBoxDataType;
import com.r3944realms.dg_lab.api.websocket.message.data.type.PowerBoxStatusCode;
import com.r3944realms.dg_lab.api.websocket.message.role.*;
import com.r3944realms.dg_lab.api.websocket.message.role.type.RoleType;
import com.r3944realms.dg_lab.utils.stringUtils.StringHandlerUtil;
import com.r3944realms.dg_lab.utils.timeTask.DgLabTimerTask;
import com.r3944realms.dg_lab.websocket.handler.AbstractDgLabPowerBoxHandlerContextWrapper;
import com.r3944realms.dg_lab.websocket.sharedData.ServerPowerBoxSharedData;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
@ -78,6 +78,8 @@ public class ServerDLPBHandlerContextWrapper extends AbstractDgLabPowerBoxHandle
Channel().add(session.channel());
Connections().put(clientId, session);
logger.info("新的 webSocket 连接已建立, 标识符为{}", clientId);
String finalClientId = clientId;
TryCatch(n -> ((ServerOperation)operation).ClientSessionBuildInHandler(finalClientId));
}
@Override
@ -297,7 +299,7 @@ public class ServerDLPBHandlerContextWrapper extends AbstractDgLabPowerBoxHandle
case CLEAR -> {
if (Connections().containsKey(targetId)) {
ChannelHandlerContext client = Connections().get(targetId);
String Channel = ((String[])argsArray)[0];
Integer Channel = ((Integer[])argsArray)[0];
String messageCommand = "clear-" + Channel;
PowerBoxMessage strengthUpdate = PowerBoxMessage.createPowerBoxMessage("msg", clientId, targetId, messageCommand, role, new WebSocketApplicationRole("Ap" + targetId));
TryCatch(n -> ((ServerOperation)operation).ClearMessageHandler(strengthUpdate));

View File

@ -16,8 +16,8 @@
package com.r3944realms.dg_lab.websocket.sharedData;
import com.r3944realms.dg_lab.utils.stringUtils.StringHandlerUtil;
import com.r3944realms.dg_lab.api.websocket.sharedData.ISharedData;
import com.r3944realms.dg_lab.utils.stringUtils.StringHandlerUtil;
import java.util.Timer;
@ -34,6 +34,7 @@ public class ClientPowerBoxSharedData implements ISharedData {
clone.delay = delay;
clone.address = address;
clone.port = port;
clone.rqCodeUrl = rqCodeUrl;
return clone;
}
@ -70,6 +71,14 @@ public class ClientPowerBoxSharedData implements ISharedData {
* The Follow b strength.
*/
public final boolean followBStrength = false;
/**
* 二维码
*/
public String rqCodeUrl = "";
/**
* 是否启用 SSL
*/
public boolean isEnableSsl = false;
/**
* Instantiates a new Client power box shared data.
@ -91,7 +100,7 @@ public class ClientPowerBoxSharedData implements ISharedData {
* @return the url
*/
public String getUrl() {
return StringHandlerUtil.buildWebSocketURL(address, port, false);
return StringHandlerUtil.buildWebSocketURL(address, port, isEnableSsl);
}

View File

@ -33,18 +33,16 @@ sourceSets {
}
dependencies {
implementation 'org.apache.logging.log4j:log4j-core:2.23.1'
implementation 'org.apache.logging.log4j:log4j-api:2.23.1'
implementation 'org.apache.logging.log4j:log4j-slf4j2-impl:2.23.1'
implementation group: 'org.realityforge.org.jetbrains.annotations', name: 'org.jetbrains.annotations', version: '1.7.0'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.17.0'
implementation group: 'com.google.guava', name: 'guava', version: '33.3.0-jre'
implementation group: 'io.netty', name: 'netty-all', version: '4.1.109.Final'
implementation group: 'com.google.code.gson', name: 'gson', version: '2.10.1'
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
implementation group: 'org.slf4j', name: 'slf4j-api', version: '2.0.16'
}
javadoc {
options.encoding = 'UTF-8'
options.charSet = 'UTF-8'
//
options.addBooleanOption('Xdoclint:none', true)
options.addStringOption('Xmaxwarns', '10')
}
tasks.register('sourcesJar', Jar) {
archiveClassifier.set('sources')
from sourceSets.main.allSource
@ -81,6 +79,21 @@ publishing {
from components.java
artifact(tasks.named("sourcesJar"))
artifact(tasks.named("javadocJar"))
pom {
name = "${project_name}"
description = "The API for ${project_name}"
url = "https://github.com/3944Realms/DG_LAB_DEVELOP"
licenses {
license {
name = 'Apache License 2.0'
url = 'https://www.apache.org/licenses/LICENSE-2.0.html'
}
}
issueManagement {
system = 'GitHub Issues'
url = 'https://github.com/3944Realms/DG_LAB_DEVELOP/issues'
}
}
}
}
}

View File

@ -39,6 +39,7 @@ public interface IDGLabManager {
* @return the shared data
*/
ISharedData getSharedData();
/**
* 获取当前单例实例运行
*

View File

@ -25,8 +25,8 @@ import com.r3944realms.dg_lab.api.message.data.PulseWaveList;
import com.r3944realms.dg_lab.api.message.data.PulseWaveListGenerator;
import com.r3944realms.dg_lab.api.websocket.message.MessageDirection;
import com.r3944realms.dg_lab.api.websocket.message.PowerBoxMessage;
import com.r3944realms.dg_lab.api.websocket.message.data.PowerBoxDataWithSingleAttachment;
import com.r3944realms.dg_lab.api.websocket.message.data.PowerBoxData;
import com.r3944realms.dg_lab.api.websocket.message.data.PowerBoxDataWithSingleAttachment;
import com.r3944realms.dg_lab.api.websocket.message.data.type.PowerBoxDataType;
import com.r3944realms.dg_lab.api.websocket.message.role.Role;

View File

@ -20,14 +20,14 @@ package com.r3944realms.dg_lab.api.message.argType;
* 修改策略
*/
public enum ChangePolicy {
/**
* 增加
*/
INCREASE(0),
/**
* 减少
*/
DECREASE(1),
DECREASE(0),
/**
* 增加
*/
INCREASE(1),
/**
* 转变
*/

View File

@ -34,8 +34,10 @@ public interface ClientOperation extends IOperation {
/**
* 客户端启动遇到错误后处理
*
* @param errorMsg 错误消息
*/
void ClientStartingErrorHandler();
void ClientStartingErrorHandler(String errorMsg);
/**
* 客户端线程关闭中处理
@ -44,8 +46,10 @@ public interface ClientOperation extends IOperation {
/**
* 客户端线程关闭中遇到错误后处理
*
* @param errorMsg 错误消息
*/
void ClientStoppingErrorHandler();
void ClientStoppingErrorHandler(String errorMsg);
/**
* 客户端线程完全关闭后处理

View File

@ -31,8 +31,10 @@ public interface ServerOperation extends IOperation {
/**
* 服务器线程开启中遇到错误后处理
*
* @param errorMessage 错误消息
*/
void ServerStartingErrorHandler();
void ServerStartingErrorHandler(String errorMessage);
/**
* 服务器线程开启后处理
@ -46,14 +48,23 @@ public interface ServerOperation extends IOperation {
/**
* 服务器线程关闭中遇到错误后处理
*
* @param errorMessage 错误消息
*/
void ServerStoppingErrorHandler();
void ServerStoppingErrorHandler(String errorMessage);
/**
* 服务器线程完全关闭后处理
*/
void ServerStoppedHandler();
/**
* 客户端会话连接触发器
*
* @param clientId the client id
*/
void ClientSessionBuildInHandler(String clientId);
/**
* 在定时器里即将被移除的UUID处理
*

View File

@ -0,0 +1,79 @@
package com.r3944realms.dg_lab.api.websocket;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
/**
* The interface Web socket server.
*/
public interface IWebSocketServer extends IWebsocketSide {
/**
* Gets listened address.
*
* @return the listened address
*/
String getListenedAddress();
/**
* Sets listened address.
*
* @param address the address
*/
void setListenedAddress(String address);
/**
* 获取监听端口
*
* @return 端口 port
*/
int getPort();
/**
* 设置监听端口
*
* @param port 端口
*/
void setPort(int port);
/**
* 启用SSL
*
* @param certificateFile 证书文件
* @param keyFile 私钥文件
*/
default void enableSSL(@NotNull File certificateFile, @NotNull File keyFile) {
enableSSL(certificateFile, keyFile,null);
}
/**
* 启用SSL
*
* @param certificateFile 证书文件
* @param keyFile 私钥文件
* @param password ssl密码
*/
void enableSSL(@NotNull File certificateFile, @NotNull File keyFile, @Nullable String password);
/**
* 禁用SSL
*/
void disableSSL();
/**
* 获取SSL是否开启
*
* @return enable boolean
*/
boolean isSSLEnabled();
/**
* 向指定的客户端发送消息
*
* @param connectId 客户端UUID
* @param message 消息
*/
void send(String connectId, Message message);
}

View File

@ -0,0 +1,72 @@
package com.r3944realms.dg_lab.api.websocket;
import com.r3944realms.dg_lab.api.websocket.message.Message;
import org.jetbrains.annotations.Nullable;
import java.io.File;
/**
* The interface Websocket client.
*/
public interface IWebsocketClient extends IWebsocketSide {
/**
* Gets address.
*
* @return the address
*/
String getAddress();
/**
* Sets address.
*
* @param address the address
*/
void setAddress(String address);
/**
* Gets port.
*
* @return the port
*/
int getPort();
/**
* Sets port.
*
* @param port the port
*/
void setPort(int port);
/**
* Enable ssl.
*/
default void enableSSL() {
enableSSL(null);
}
/**
* Enable ssl.
*
* @param certificateFile the certificate file
*/
void enableSSL(@Nullable File certificateFile);
/**
* Disable ssl.
*/
void disableSSL();
/**
* Is ssl enabled boolean.
*
* @return the boolean
*/
boolean isSSLEnabled();
/**
* 向所连接的服务器发送消息
*
* @param message 消息
*/
void send(Message message);
}

View File

@ -0,0 +1,72 @@
package com.r3944realms.dg_lab.api.websocket;
import com.r3944realms.dg_lab.api.manager.Status;
/**
* The interface Websocket side.
*/
public interface IWebsocketSide {
/**
* 获取状态
*
* @return the status
*/
Status getStatus();
/**
* 设置状态
*
* @param status 状态
*/
void setStatus(Status status);
/**
* Init.
*/
void init();
/**
* Start.
*/
void start();
/**
* Stop.
*/
void stop();
/**
* On starting.
*/
void onStarting();
/**
* On stopping.
*/
void onStopping();
/**
* On starting error.
*
* @param msg the msg
*/
void onStartingError(String msg);
/**
* On stopping error.
*
* @param msg the msg
*/
void onStoppingError(String msg);
/**
* On started.
*/
void onStarted();
/**
* On stopped.
*/
void onStopped();
}

View File

@ -19,14 +19,19 @@ package com.r3944realms.dg_lab.api.websocket.message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.Expose;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.r3944realms.dg_lab.api.websocket.message.data.IData;
import com.r3944realms.dg_lab.api.websocket.message.data.adapter.IDataTypeAdapterFactory;
import com.r3944realms.dg_lab.api.websocket.message.role.Role;
import com.r3944realms.dg_lab.api.websocket.message.role.RoleDeserializer;
import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicReference;
/**
* 消息带有方向和有效负载消息
@ -52,6 +57,24 @@ public abstract class Message implements Serializable {
gsonBuilder.registerTypeAdapter(Role.class, new RoleDeserializer());
gsonBuilder.registerTypeAdapter(MessageDirection.class, new MessageDirectionDeserializer());
gsonBuilder.registerTypeAdapterFactory(new IDataTypeAdapterFactory());
// 注册 AtomicReference 的适配器
gsonBuilder.registerTypeAdapter(AtomicReference.class, new TypeAdapter<AtomicReference<?>>() {
@Override
public void write(JsonWriter out, AtomicReference<?> value) throws IOException {
if (value == null || value.get() == null) {
out.nullValue();
} else {
gson.toJson(value.get(), value.get().getClass(), out);
}
}
@Override
public AtomicReference<?> read(JsonReader in) throws IOException {
Object obj = gson.fromJson(in, Object.class);
return new AtomicReference<>(obj);
}
});
gson = gsonBuilder.create();
}

View File

@ -18,7 +18,6 @@ package com.r3944realms.dg_lab.api.websocket.message;
import com.r3944realms.dg_lab.api.websocket.message.role.*;
import java.io.Serializable;
/**

View File

@ -38,7 +38,14 @@ public class PowerBoxMessage extends Message {
/**
* The Invalid message json.
*/
static final String INVALID_MESSAGE_JSON = gson.toJson(PowerBoxData.createPowerBoxData("error","","",""));
private static class LazyInvalidJsonHolder {
/**
* The Value.
*/
static final String VALUE =
gson.toJson(PowerBoxData.createPowerBoxData("error", "", "", ""));
}
/**
* Instantiates a new Power box message.
@ -168,7 +175,7 @@ public class PowerBoxMessage extends Message {
@Override
public String getInvalidMessageJson() {
return INVALID_MESSAGE_JSON;
return LazyInvalidJsonHolder.VALUE;
}
@Override

View File

@ -16,6 +16,9 @@
package com.r3944realms.dg_lab.api.websocket.message.data;
/**
* The enum Data type.
*/
public enum DataType {
/**
* Power box att data type.
@ -29,6 +32,7 @@ public enum DataType {
* Power box data type.
*/
POWER_BOX;
/**
* Gets type from string.
*

View File

@ -16,6 +16,9 @@
package com.r3944realms.dg_lab.api.websocket.message.data;
/**
* The interface Data.
*/
public interface IData {
/**

View File

@ -16,6 +16,7 @@
package com.r3944realms.dg_lab.api.websocket.message.data;
import com.google.gson.annotations.Expose;
import com.r3944realms.dg_lab.api.websocket.message.data.type.PowerBoxDataType;
import com.r3944realms.dg_lab.api.websocket.message.data.type.PowerBoxStatusCode;
@ -35,7 +36,9 @@ public class PowerBoxData implements IData {
private final String clientId;
private final String targetId;
private final String message;
AtomicReference<String> inValidReason = new AtomicReference<>(getInvalidReason());
@Expose(serialize = false, deserialize = false)
private final transient AtomicReference<String> inValidReason = new AtomicReference<>(getInvalidReason());
/**
* Instantiates a new Power box data.
*

View File

@ -4,8 +4,8 @@ plugins {
id("maven-publish")
}
group = "top.r3944realms.superleadrope"
version = "1.0-SNAPSHOT"
group = "${project_version}"
version = "${project_version}"
allprojects {
repositories {
@ -16,6 +16,7 @@ allprojects {
subprojects {
apply {
plugin('java')
plugin("maven-publish")
}
java {
@ -25,11 +26,42 @@ subprojects {
}
dependencies {
testImplementation(platform("org.junit:junit-bom:5.10.0"))
testImplementation("org.junit.jupiter:junit-jupiter")
implementation 'org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:1.7.0'
implementation 'org.apache.logging.log4j:log4j-core:2.23.1'
implementation 'org.apache.logging.log4j:log4j-api:2.23.1'
implementation 'org.apache.logging.log4j:log4j-slf4j2-impl:2.23.1'
implementation 'org.apache.commons:commons-lang3:3.17.0'
implementation 'com.google.guava:guava:33.3.0-jre'
implementation 'io.netty:netty-all:4.1.109.Final'
implementation 'com.google.code.gson:gson:2.10.1'
implementation 'org.slf4j:slf4j-api:2.0.16'
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
tasks.test {
useJUnitPlatform()
}
tasks.withType(PublishToMavenRepository) {
dependsOn assemble
}
publishing {
repositories {
maven {
name = "local"
url = layout.buildDirectory.dir("repo")
}
maven {
name = 'LTDNexus'
url = 'https://nexus.bot.leisuretimedock.top/repository/maven-releases/'
credentials {
username = System.getenv('LTDNexusUsername') ?: ''
password = System.getenv('LTDNexusPassword') ?: ''
}
}
}
}
}

View File

@ -1,13 +1,13 @@
# Gradle settings
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=true
org.gradle.daemon=false
org.gradle.configureondemand=true
org.gradle.caching=true
org.gradle.configuration-cache=true
org.gradle.caching=false
org.gradle.configuration-cache=false
org.gradle.configuration-cache.problems=warn
# ROOT
project_name=DgLab
project_version=4.2.8.16
project_version=4.4.14.19
project_group=top.r3944realms.dg_lab
# API

Binary file not shown.

View File

@ -1,6 +1,7 @@
#Sun Sep 22 17:25:46 CST 2024
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-8.12-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
gradlew vendored Normal file
View File

@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored Normal file
View File

@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -2,6 +2,44 @@
统一用4位版本对于测试性更新统一在其后加-Beta。
修复问题更新为加0.0.0.1,添加/移除新特性加0.0.1.0小部分重构更新加0.1.0.0大量重构加1.0.0.0
2026-04-20-1
project_version=4.4.14.19
* 修复clear指令构建命令时抛出转型异常导致无法正确发送指令
* 修复ChangePolicy增加和减小index写反的问题
2025-09-29-1
project_version=4.4.14.18
* 提取Server/Client接口
* 重命名方法starting 变为 onStarting等
* Server添加设置监听地址功能
2025-09-29-1
project_version=4.3.12.18
* 新增操作ServerOperation类中方法会话建立Handler已在与客户端会话创建后可进行操作
* 修改错误消息提醒
2025-09-23-1
project_version=4.3.11.18
* 添加操作Operation类的Error方法错误的参数同时移除无参方法
2025-09-21-4
project_version=4.2.11.18
* 添加服务器对SSL密码参数支持
2025-09-21-3
project_version=4.2.10.18
* 添加ClientPowerBoxSharedData添加新字段 isEnableSsl,用于WS地址协议头判断
* 让PowerBoxWSClient继承了父类的#enableSSL #disableSSL方法以适配添加ClientPowerBoxSharedData添加新字段的字段 isEnableSsl
2025-09-21-2
project_version=4.2.10.17
* 修正 DGPBClientManager 的实现接口为com.r3944realms.dg_lab.api.manager.IDGLabManager
* 在ClientPowerBoxSharedData添加新字段rqCodeUrl用于辅助访问二维码Url
2025-09-21-1
project_version=4.2.9.16
* 添加了SSL支持
2025-09-13-1
project_version=4.2.8.16
* 重构项目结构