Repository navigation
Expand file tree
/
Copy pathGame.java
More file actions
110 lines (94 loc) · 3.56 KB
/
Copy pathGame.java
File metadata and controls
110 lines (94 loc) · 3.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import Minecraft.Host;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class Game {
private final Host host;
private Process serverProcess;
private SToper stoper;
private PrintWriter processInputWriter;
public Game(Host host) {
this.host = host;
}
public void start() {
File codeDir = host.getServerCodeDir();
File jarFile = new File(codeDir, "server.jar");
if (!jarFile.exists()) {
System.err.println("[Error] Minecraft/Code/server.jar が見つかりません。");
return;
}
setupEula(codeDir);
try {
ProcessBuilder pb = new ProcessBuilder(
"java",
"-Xmx2048M",
"-Xms1048M",
"-jar",
"server.jar",
"nogui"
);
pb.directory(codeDir);
pb.redirectErrorStream(true);
serverProcess = pb.start();
stoper = new SToper(serverProcess);
processInputWriter = new PrintWriter(new OutputStreamWriter(serverProcess.getOutputStream()), true);
new Thread(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(serverProcess.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("[MC] " + line);
if (line.contains("logged in") || line.contains("joined the game")) {
String playerName = parsePlayerName(line);
stoper.onPlayerJoin(playerName);
}
else if (line.contains("left the game")) {
String playerName = parsePlayerName(line);
stoper.onPlayerLeave(playerName);
}
else if (line.contains("Done (") && line.contains("For help, type")) {
if (stoper.getOnlinePlayers() == 0) {
stoper.pauseServer();
}
}
}
} catch (IOException e) {
}
}).start();
} catch (IOException e) {
System.err.println("[Error] サーバー起動エラー: " + e.getMessage());
}
}
private String parsePlayerName(String logLine) {
try {
String[] parts = logLine.split("]: ");
if (parts.length > 1) {
String namePart = parts[1].trim();
return namePart.split("\\[")[0].split(" ")[0];
}
} catch (Exception e) {
}
return "UnknownPlayer";
}
private void setupEula(File dir) {
Path eulaPath = dir.toPath().resolve("eula.txt");
if (!Files.exists(eulaPath)) {
try {
Files.writeString(eulaPath, "eula=true\n");
} catch (IOException ignored) {}
}
}
public void sendCommand(String command) {
if (stoper != null && stoper.isPaused()) {
stoper.resumeServer();
}
if (processInputWriter != null && isRunning()) {
processInputWriter.println(command);
}
}
public boolean isRunning() {
return serverProcess != null && serverProcess.isAlive();
}
public SToper getStoper() {
return stoper;
}
}