Skip to content

Commit

Permalink
feat(Communication): 重构通讯代码,优化异常处理
Browse files Browse the repository at this point in the history
  • Loading branch information
shulng committed Sep 18, 2024
1 parent 708ebf2 commit 7863d28
Showing 1 changed file with 9 additions and 32 deletions.
41 changes: 9 additions & 32 deletions src/main/java/cc/baka9/catseedlogin/bungee/Communication.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package cc.baka9.catseedlogin.bungee;

import java.net.Socket;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

import net.md_5.bungee.api.ProxyServer;
import cc.baka9.catseedlogin.util.CommunicationAuth;
import net.md_5.bungee.api.ProxyServer;

/**
* bc 与 bukkit 的通讯交流
Expand All @@ -16,56 +16,33 @@ public class Communication {
private static final int PORT = Config.Port;

public static int sendConnectRequest(String playerName) {
Socket socket = null;
BufferedWriter writer = null;
try {
socket = getSocket();
writer = getSocketBufferedWriter(socket);
try (Socket socket = new Socket(HOST, PORT);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
writeMessage(writer, "Connect", playerName);
return socket.getInputStream().read();
} catch (IOException e) {
handleIOException(e);
ProxyServer.getInstance().getLogger().severe("发生 I/O 异常: " + e.getMessage());
return 0;
}
}

public static void sendKeepLoggedInRequest(String playerName) {
Socket socket = null;
BufferedWriter writer = null;
try {
socket = getSocket();
writer = getSocketBufferedWriter(socket);
try (Socket socket = new Socket(HOST, PORT);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
long currentTime = System.currentTimeMillis();
String time = String.valueOf(currentTime);
String sign = CommunicationAuth.encryption(playerName, time, Config.AuthKey);
writeMessage(writer, "KeepLoggedIn", playerName, time, sign);
} catch (IOException e) {
handleIOException(e);
}
}

private static Socket getSocket() throws IOException {
try {
return new Socket(HOST, PORT);
} catch (IOException e) {
ProxyServer.getInstance().getLogger().warning("§c请检查装载登录插件的子服是否在 bungeecord.yml 中开启了bungeecord功能,以及Host和Port是否与bc端的配置相同");
throw e;
ProxyServer.getInstance().getLogger().severe("发生 I/O 异常: " + e.getMessage());
}
}

private static BufferedWriter getSocketBufferedWriter(Socket socket) throws IOException {
return new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}

private static void writeMessage(BufferedWriter writer, String... messages) throws IOException {
for (String message : messages) {
writer.write(message);
writer.newLine();
}
writer.flush();
}

private static void handleIOException(IOException e) {
ProxyServer.getInstance().getLogger().severe("发生 I/O 异常: " + e.getMessage());
}
}

0 comments on commit 7863d28

Please sign in to comment.