-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main.java
126 lines (110 loc) · 3.32 KB
/
Main.java
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import com.pty4j.PtyProcessBuilder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
private static Process serverProcess;
private static BufferedWriter printer;
public static void main(String[] args) {
scanConsole();
start(args);
}
/**
* Scan the cmd for user input
*/
private static void scanConsole() {
new Thread(() -> {
try {
String line;
BufferedReader sys = new BufferedReader(new InputStreamReader(System.in));
while ((line = sys.readLine()) != null) {
if (serverProcess.isAlive()) {
write(line);
} else {
log("The garry's mod server is off, stopping the java process");
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
/**
* Send a command to the garry's mod server.
*
* @param data The command.
*/
private static void write(String data) {
try {
if (printer != null) {
printer.write(data + "\n");
printer.flush();
log(">" + data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Use to start de garry's mod server
*
* @param cmd the arg use to start the process
*/
private static void start(String[] cmd) {
try {
log("Gmod process is going to start");
serverProcess = new PtyProcessBuilder(cmd)
//.setDirectory("/home/jeu/Steam/Gmod/") // use the dir where the jar is
.start();
printer = new BufferedWriter(new OutputStreamWriter(serverProcess.getOutputStream()));
scan(new BufferedReader(new InputStreamReader(serverProcess.getInputStream())));
processExitDetector();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Scan the given buffer in a new thread
*
* @param br the buffer
*/
private static void scan(BufferedReader br) {
new Thread(() -> {
try {
while (serverProcess.isAlive()) {
String line;
if ((line = br.readLine()) != null) {
log(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
/**
* The function wait until the process stop
*/
private static void processExitDetector() {
new Thread(() -> {
if (serverProcess.isAlive()) {
try {
serverProcess.waitFor();
log("Gmod has stopped");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
static SimpleDateFormat date = new SimpleDateFormat("[hh:mm:ss.SSS]");
/**
* log a message
*
* @param s the message
*/
public static void log(String s) {
System.out.println(date.format(new Date(System.currentTimeMillis())) + s);
}
}