Calenria
Braumeister
Erstmal der Code:
Wie ich finde sieht das ganze noch recht hässlich aus mit dem ganzen Hex/Char/Byte zeug, jemand eine Idee für eine elegantere Lösung?
Code:
public class Status {
public static void main(String[] args) throws IOException {
HashMap<String, String> status = serverStatus("serverip", 25565);
for (String key : status.keySet()) {
System.out.println(key + ":" + status.get(key));
}
}
public static HashMap<String, String> serverStatus(String host, Integer port) throws IOException {
Socket socket = null;
DataOutputStream out = null;
DataInputStream in = null;
HashMap<String, String> data = new HashMap<String, String>();
try {
socket = new Socket(host, 25565);
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + host);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to:" + host);
}
out.write(hexStringToByteArray("FE"));
byte[] b = new byte[241];
in.read(b, 0, 241);
StringBuffer buffer = new StringBuffer();
for (int i = 4; i < b.length; i++) {
if (b[i] != 0) {
buffer.append((char) b[i]);
}
}
String[] split = buffer.toString().split(String.valueOf((char) -89));
data.put("motd", split[0]);
data.put("players", split[1]);
data.put("maxplayers", split[2]);
out.close();
in.close();
socket.close();
return data;
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
Wie ich finde sieht das ganze noch recht hässlich aus mit dem ganzen Hex/Char/Byte zeug, jemand eine Idee für eine elegantere Lösung?