refactor(提取接口): 提取了Client/Server类的方法接口

This commit is contained in:
叁玖领域 2026-01-31 19:24:03 +08:00
parent 748474de86
commit ea04a3e9fc
22 changed files with 657 additions and 332 deletions

View File

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

@ -25,19 +25,6 @@ repositories {
dependencies { dependencies {
// Common CommonApi // Common CommonApi
api project(':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 // Sources JAR

View File

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

View File

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

View File

@ -62,8 +62,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData; this.sharedData = sharedData;
this.operation = operation; this.operation = operation;
this.role = role; this.role = role;
sharedData.address = this.Address; sharedData.address = this.address;
sharedData.port = this.Port; sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, false); contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, false);
} }
@ -82,8 +82,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData; this.sharedData = sharedData;
this.operation = operation; this.operation = operation;
this.role = role; this.role = role;
sharedData.address = this.Address; sharedData.address = this.address;
sharedData.port = this.Port; sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, false); contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, false);
} }
@ -123,8 +123,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData; this.sharedData = sharedData;
this.operation = operation; this.operation = operation;
this.role = role; this.role = role;
sharedData.address = this.Address; sharedData.address = this.address;
sharedData.port = this.Port; sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, useRoleMsgMode); contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, useRoleMsgMode);
} }
@ -144,8 +144,8 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
this.sharedData = sharedData; this.sharedData = sharedData;
this.operation = operation; this.operation = operation;
this.role = role; this.role = role;
sharedData.address = this.Address; sharedData.address = this.address;
sharedData.port = this.Port; sharedData.port = this.port;
contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, useRoleMsgMode); contextWrapper = new ClientDLPBHandlerContextWrapper(sharedData, role, operation, useRoleMsgMode);
} }
@ -178,35 +178,41 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
} }
@Override @Override
protected void starting() { public void init() {
}
@Override
public void onStarting() {
operation.ClientStartingHandler(); operation.ClientStartingHandler();
} }
@Override @Override
protected void startingError(String msg) { public void onStartingError(String msg) {
operation.ClientStartingErrorHandler(msg); operation.ClientStartingErrorHandler(msg);
} }
@Override @Override
protected void started() { public void onStarted() {
operation.ClientStartedHandler(); operation.ClientStartedHandler();
} }
@Override @Override
protected void stopping() { public void onStopping() {
operation.ClientStoppingHandler(); operation.ClientStoppingHandler();
} }
@Override @Override
protected void stoppingError(String msg) { public void onStoppingError(String msg) {
operation.ClientStoppingErrorHandler(msg); operation.ClientStoppingErrorHandler(msg);
} }
@Override @Override
protected void stopped() { public void onStopped() {
operation.ClientStoppedHandler(); operation.ClientStoppedHandler();
} }
@Override @Override
public void enableSSL() { public void enableSSL() {
super.enableSSL(); super.enableSSL();
@ -219,10 +225,12 @@ public class PowerBoxWSClient extends AbstractWebSocketClient {
sharedData.isEnableSsl = false; sharedData.isEnableSsl = false;
} }
@Override @Override
public void send(Message message) { public void send(Message message) {
if(message instanceof PowerBoxMessage PBMessage) { if(message instanceof PowerBoxMessage PBMessage) {
this.ClientChannel.writeAndFlush(new TextWebSocketFrame(PBMessage.getMsgJson())); this.clientChannel.writeAndFlush(new TextWebSocketFrame(PBMessage.getMsgJson()));
} else { } else {
logger.error("Message is not a PowerBoxMessage"); logger.error("Message is not a PowerBoxMessage");
} }

View File

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

View File

@ -65,7 +65,7 @@ public class ClientPowerBoxSharedData implements ISharedData {
/** /**
* The Follow a strength. * The Follow a strength.
*/ */
//跟随AB的软上限 //跟随AB的软上限
public final boolean followAStrength = false; public final boolean followAStrength = false;
/** /**
* The Follow b strength. * The Follow b strength.
@ -79,6 +79,7 @@ public class ClientPowerBoxSharedData implements ISharedData {
* 是否启用 SSL * 是否启用 SSL
*/ */
public boolean isEnableSsl = false; public boolean isEnableSsl = false;
/** /**
* Instantiates a new Client power box shared data. * Instantiates a new Client power box shared data.
* *

View File

@ -33,18 +33,8 @@ sourceSets {
} }
dependencies { 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'
} }
tasks.register('sourcesJar', Jar) { tasks.register('sourcesJar', Jar) {
archiveClassifier.set('sources') archiveClassifier.set('sources')
from sourceSets.main.allSource from sourceSets.main.allSource

View File

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

View File

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

View File

@ -31,6 +31,7 @@ public interface ServerOperation extends IOperation {
/** /**
* 服务器线程开启中遇到错误后处理 * 服务器线程开启中遇到错误后处理
*
* @param errorMessage 错误消息 * @param errorMessage 错误消息
*/ */
void ServerStartingErrorHandler(String errorMessage); void ServerStartingErrorHandler(String errorMessage);
@ -47,6 +48,7 @@ public interface ServerOperation extends IOperation {
/** /**
* 服务器线程关闭中遇到错误后处理 * 服务器线程关闭中遇到错误后处理
*
* @param errorMessage 错误消息 * @param errorMessage 错误消息
*/ */
void ServerStoppingErrorHandler(String errorMessage); void ServerStoppingErrorHandler(String errorMessage);
@ -58,6 +60,8 @@ public interface ServerOperation extends IOperation {
/** /**
* 客户端会话连接触发器 * 客户端会话连接触发器
*
* @param clientId the client id
*/ */
void ClientSessionBuildInHandler(String clientId); void ClientSessionBuildInHandler(String clientId);

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.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.Expose; 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.IData;
import com.r3944realms.dg_lab.api.websocket.message.data.adapter.IDataTypeAdapterFactory; 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.Role;
import com.r3944realms.dg_lab.api.websocket.message.role.RoleDeserializer; import com.r3944realms.dg_lab.api.websocket.message.role.RoleDeserializer;
import java.io.IOException;
import java.io.Serial; import java.io.Serial;
import java.io.Serializable; 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(Role.class, new RoleDeserializer());
gsonBuilder.registerTypeAdapter(MessageDirection.class, new MessageDirectionDeserializer()); gsonBuilder.registerTypeAdapter(MessageDirection.class, new MessageDirectionDeserializer());
gsonBuilder.registerTypeAdapterFactory(new IDataTypeAdapterFactory()); 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(); gson = gsonBuilder.create();
} }

View File

@ -38,7 +38,14 @@ public class PowerBoxMessage extends Message {
/** /**
* The Invalid message json. * 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. * Instantiates a new Power box message.
@ -168,7 +175,7 @@ public class PowerBoxMessage extends Message {
@Override @Override
public String getInvalidMessageJson() { public String getInvalidMessageJson() {
return INVALID_MESSAGE_JSON; return LazyInvalidJsonHolder.VALUE;
} }
@Override @Override

View File

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

View File

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

View File

@ -16,6 +16,7 @@
package com.r3944realms.dg_lab.api.websocket.message.data; 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.PowerBoxDataType;
import com.r3944realms.dg_lab.api.websocket.message.data.type.PowerBoxStatusCode; 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 clientId;
private final String targetId; private final String targetId;
private final String message; 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. * Instantiates a new Power box data.
* *

View File

@ -25,8 +25,18 @@ subprojects {
} }
dependencies { dependencies {
testImplementation(platform("org.junit:junit-bom:5.10.0")) implementation 'org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:1.7.0'
testImplementation("org.junit.jupiter:junit-jupiter") 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 { tasks.test {

View File

@ -7,7 +7,7 @@ org.gradle.configuration-cache=true
org.gradle.configuration-cache.problems=warn org.gradle.configuration-cache.problems=warn
# ROOT # ROOT
project_name=DgLab project_name=DgLab
project_version=4.3.12.18 project_version=4.3.13.18
project_group=top.r3944realms.dg_lab project_group=top.r3944realms.dg_lab
# API # API