Skip to content

Commit b18e4cb

Browse files
committed
测试代码
1 parent 6a79960 commit b18e4cb

File tree

4 files changed

+366
-0
lines changed

4 files changed

+366
-0
lines changed

build.gradle

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@ shadowJar {
4343
}
4444
test {
4545
useJUnitPlatform()
46+
configurations.configureEach {
47+
exclude group: 'org.apache.logging.log4j', module: 'log4j-slf4j-impl'
48+
}
4649
}
4750
jar {
4851
manifest.attributes([
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
/*******************************************************************************
2+
* Copyright (c) 2024-2025 R3944Realms. All rights reserved.
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
******************************************************************************/
16+
17+
package com.r3944realms.dg_lab.extend;
18+
19+
import com.r3944realms.dg_lab.extend.websocket.CalculatorClient;
20+
import com.r3944realms.dg_lab.extend.websocket.CalculatorServer;
21+
22+
import java.util.Scanner;
23+
import java.util.concurrent.CountDownLatch;
24+
25+
public class CalculatorApp {
26+
public static void main(String[] args) {
27+
Scanner scanner = new Scanner(System.in);
28+
29+
System.out.println("选择模式: 1.服务器 2.客户端");
30+
int mode = scanner.nextInt();
31+
scanner.nextLine(); // 消耗换行符
32+
33+
if (mode == 1) {
34+
startServerMode(scanner);
35+
} else if (mode == 2) {
36+
startClientMode(scanner);
37+
}
38+
39+
scanner.close();
40+
}
41+
42+
private static void startServerMode(Scanner scanner) {
43+
System.out.println("输入服务器端口(默认9000):");
44+
String portInput = scanner.nextLine();
45+
int port = portInput.isEmpty() ? 9000 : Integer.parseInt(portInput);
46+
47+
CalculatorServer server = new CalculatorServer(port);
48+
server.start();
49+
50+
System.out.println("服务器已启动,输入'stop'停止...");
51+
while (true) {
52+
String input = scanner.nextLine();
53+
if ("stop".equalsIgnoreCase(input)) {
54+
server.stop();
55+
break;
56+
}
57+
}
58+
}
59+
60+
private static void startClientMode(Scanner scanner) {
61+
System.out.println("输入服务器地址(默认localhost):");
62+
String address = scanner.nextLine();
63+
if (address.isEmpty()) address = "localhost";
64+
65+
System.out.println("输入服务器端口(默认9000):");
66+
String portInput = scanner.nextLine();
67+
int port = portInput.isEmpty() ? 9000 : Integer.parseInt(portInput);
68+
69+
CalculatorClient client = new CalculatorClient(address, port);
70+
client.start();
71+
72+
// 使用CountDownLatch等待客户端线程结束
73+
CountDownLatch latch = new CountDownLatch(1);
74+
75+
// 添加关闭钩子
76+
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
77+
client.stop();
78+
latch.countDown();
79+
}));
80+
81+
System.out.println("客户端已连接,输入'exit'退出...");
82+
try {
83+
latch.await(); // 等待直到收到退出信号
84+
} catch (InterruptedException e) {
85+
Thread.currentThread().interrupt();
86+
}
87+
}
88+
}
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
/*******************************************************************************
2+
* Copyright (c) 2024-2025 R3944Realms. All rights reserved.
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
******************************************************************************/
16+
17+
package com.r3944realms.dg_lab.extend.websocket;
18+
19+
import com.r3944realms.dg_lab.websocket.AbstractWebSocketClient;
20+
import com.r3944realms.dg_lab.websocket.message.Message;
21+
import io.netty.channel.ChannelHandlerContext;
22+
import io.netty.channel.ChannelPipeline;
23+
import io.netty.channel.SimpleChannelInboundHandler;
24+
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
25+
26+
import java.util.Scanner;
27+
import java.util.concurrent.atomic.AtomicBoolean;
28+
29+
public class CalculatorClient extends AbstractWebSocketClient {
30+
private Scanner scanner;
31+
private final AtomicBoolean isRunning = new AtomicBoolean(true);
32+
private final AtomicBoolean isProcessing = new AtomicBoolean(false);
33+
private final AtomicBoolean shouldPrompt = new AtomicBoolean(true);
34+
35+
public CalculatorClient(String address, int port) {
36+
super(address, port);
37+
}
38+
39+
@Override
40+
protected void MessagePipeLineHandler(ChannelPipeline pipeline) {
41+
pipeline.addLast(new SimpleChannelInboundHandler<TextWebSocketFrame>() {
42+
@Override
43+
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
44+
String response = frame.text();
45+
processServerResponse(response);
46+
isProcessing.set(false);
47+
if (isRunning.get()) {
48+
shouldPrompt.set(true);
49+
promptForInput();
50+
}
51+
}
52+
53+
@Override
54+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
55+
System.out.println("\n连接错误: " + cause.getMessage());
56+
stop();
57+
}
58+
});
59+
}
60+
61+
@Override
62+
protected void start0() {
63+
this.scanner = new Scanner(System.in);
64+
System.out.println("客户端准备就绪");
65+
promptForInput();
66+
}
67+
68+
private synchronized void promptForInput() {
69+
if (!isRunning.get() || !shouldPrompt.get()) {
70+
return;
71+
}
72+
73+
shouldPrompt.set(false);
74+
System.out.print("\n请输入两个整数(用逗号分隔),或输入'exit'退出: ");
75+
76+
new Thread(() -> {
77+
try {
78+
String input = scanner.nextLine();
79+
80+
if ("exit".equalsIgnoreCase(input)) {
81+
stop();
82+
return;
83+
}
84+
85+
if (isProcessing.get()) {
86+
System.out.println("请等待上一个请求完成");
87+
shouldPrompt.set(true);
88+
promptForInput();
89+
return;
90+
}
91+
92+
if (ClientChannel != null && ClientChannel.isActive()) {
93+
isProcessing.set(true);
94+
ClientChannel.writeAndFlush(new TextWebSocketFrame(input));
95+
} else {
96+
System.out.println("连接不可用,请重新连接");
97+
shouldPrompt.set(true);
98+
promptForInput();
99+
}
100+
} catch (Exception e) {
101+
if (!e.getMessage().contains("No line found")) {
102+
System.out.println("输入错误: " + e.getMessage());
103+
}
104+
shouldPrompt.set(true);
105+
promptForInput();
106+
}
107+
}).start();
108+
}
109+
110+
private void processServerResponse(String response) {
111+
try {
112+
String[] results = response.split(",");
113+
114+
if (results.length == 4 && !results[0].startsWith("错误")) {
115+
System.out.println("\n计算结果:");
116+
System.out.println("和: " + results[0]);
117+
System.out.println("差: " + results[1]);
118+
System.out.println("积: " + results[2]);
119+
System.out.println("商: " + ("NaN".equals(results[3]) ? "不能除以零" : results[3]));
120+
} else {
121+
System.out.println("\n错误: " + response);
122+
}
123+
} catch (Exception e) {
124+
System.out.println("\n处理响应时出错: " + e.getMessage());
125+
}
126+
}
127+
128+
@Override
129+
protected void starting() {
130+
System.out.println("正在启动客户端...");
131+
}
132+
133+
@Override
134+
protected void startingError() {
135+
System.out.println("客户端启动失败");
136+
}
137+
138+
@Override
139+
protected void started() {
140+
System.out.println("已连接到服务器");
141+
}
142+
143+
@Override
144+
protected void stopping() {
145+
isRunning.set(false);
146+
System.out.println("\n正在停止客户端...");
147+
}
148+
149+
@Override
150+
protected void stoppingError() {
151+
System.out.println("客户端终止失败");
152+
}
153+
154+
@Override
155+
protected void stopped() {
156+
System.out.println("客户端已停止");
157+
if (scanner != null) {
158+
scanner.close();
159+
}
160+
}
161+
162+
@Override
163+
public void send(Message message) {
164+
throw new UnsupportedOperationException("Not supported yet.");
165+
}
166+
}
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/*******************************************************************************
2+
* Copyright (c) 2024-2025 R3944Realms. All rights reserved.
3+
* <p>
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
* <p>
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
* <p>
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
******************************************************************************/
16+
17+
package com.r3944realms.dg_lab.extend.websocket;
18+
19+
import com.r3944realms.dg_lab.websocket.AbstractWebSocketServer;
20+
import com.r3944realms.dg_lab.websocket.message.Message;
21+
import io.netty.channel.ChannelHandlerContext;
22+
import io.netty.channel.ChannelPipeline;
23+
import io.netty.channel.SimpleChannelInboundHandler;
24+
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
25+
import org.jetbrains.annotations.NotNull;
26+
27+
public class CalculatorServer extends AbstractWebSocketServer {
28+
public CalculatorServer(int port) {
29+
super(port);
30+
}
31+
32+
@Override
33+
protected void MessagePipeLineHandler(ChannelPipeline pipeline) {
34+
pipeline.addLast(new SimpleChannelInboundHandler<TextWebSocketFrame>() {
35+
@Override
36+
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
37+
try {
38+
String[] parts = frame.text().split(",");
39+
if (parts.length != 2) {
40+
ctx.channel().writeAndFlush(new TextWebSocketFrame("错误: 需要两个数字"));
41+
return;
42+
}
43+
44+
String response = getString(parts);
45+
ctx.channel().writeAndFlush(new TextWebSocketFrame(response));
46+
} catch (NumberFormatException e) {
47+
ctx.channel().writeAndFlush(new TextWebSocketFrame("错误: 无效的数字格式"));
48+
} catch (Exception e) {
49+
ctx.channel().writeAndFlush(new TextWebSocketFrame("错误: 处理请求时发生错误"));
50+
logger.error("Error processing calculator request", e);
51+
}
52+
}
53+
54+
private static @NotNull String getString(String[] parts) {
55+
int num1 = Integer.parseInt(parts[0]);
56+
int num2 = Integer.parseInt(parts[1]);
57+
58+
int sum = num1 + num2;
59+
int difference = num1 - num2;
60+
int product = num1 * num2;
61+
String quotient;
62+
63+
if (num2 != 0) {
64+
quotient = String.valueOf((double) num1 / num2);
65+
} else {
66+
quotient = "NaN";
67+
}
68+
69+
return sum + "," + difference + "," + product + "," + quotient;
70+
}
71+
});
72+
}
73+
74+
// 其他生命周期方法保持不变...
75+
@Override
76+
protected void starting() {
77+
logger.info("Calculator Server is starting...");
78+
}
79+
80+
@Override
81+
protected void startingError() {
82+
logger.error("Calculator Server failed to start");
83+
}
84+
85+
@Override
86+
protected void started() {
87+
logger.info("Calculator Server started successfully");
88+
}
89+
90+
@Override
91+
protected void stopping() {
92+
logger.info("Calculator Server is stopping...");
93+
}
94+
95+
@Override
96+
protected void stoppingError() {
97+
logger.error("Error occurred while stopping Calculator Server");
98+
}
99+
100+
@Override
101+
protected void stopped() {
102+
logger.info("Calculator Server stopped successfully");
103+
}
104+
105+
@Override
106+
public void send(String clientId, Message message) {
107+
throw new UnsupportedOperationException("Not supported yet.");
108+
}
109+
}

0 commit comments

Comments
 (0)