SteamWar/FightSystem
Archiviert
13
1

RecordSystem (Beta) #199

Manuell gemergt
Lixfel hat 40 Commits von recordSystem nach master 2020-11-01 20:11:45 +01:00 zusammengeführt
Nur Änderungen aus Commit 19d7d719e8 werden angezeigt - Alle Commits anzeigen

Datei anzeigen

@ -0,0 +1,131 @@
package de.steamwar.fightsystem.record;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SpectateConnection {
public static SpectateConnection getInstance() {
return spectateConnection;
}
public static SpectateConnection build(String ip, int port) {
spectateConnection = new SpectateConnection(ip, port);
return spectateConnection;
}
public static void cleanUp() {
if (spectateConnection == null) {
return;
}
spectateConnection.internalCleanUp();
spectateConnection = null;
}
private static SpectateConnection spectateConnection = null;
private void internalCleanUp() {
try {
socket.close();
inputStream.close();
outputStream.close();
} catch (IOException e) {
errorCode = 2;
}
}
/**
* 0 - OK
* 1 - No Connect
* 2 - Error while cleanup
* 3 - Error while reading
* 4 - Error while writing
* 5 - Error while flushing
*/
private int errorCode = 0;
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
private SpectateConnection(String ip, int port) {
try {
this.socket = new Socket(ip, port);
this.inputStream = socket.getInputStream();
this.outputStream = socket.getOutputStream();
} catch (IOException e) {
errorCode = 1;
}
}
public int getErrorCode() {
return errorCode;
}
public InputStream getInputStream() {
return inputStream;
}
public OutputStream getOutputStream() {
return outputStream;
}
public int read() {
try {
return inputStream.read();
} catch (IOException e) {
errorCode = 3;
return -2;
}
}
public byte[] lazyRead(int length) {
try {
byte[] bytes = new byte[length];
inputStream.read(bytes);
return bytes;
} catch (IOException e) {
errorCode = 3;
return new byte[length];
}
}
public byte[] read(int length) {
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++) {
bytes[i] = (byte) read();
if (errorCode != 0) {
break;
}
}
return bytes;
}
public void write(byte b) {
try {
outputStream.write(b);
} catch (IOException e) {
errorCode = 4;
}
}
public void write(byte... bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
errorCode = 4;
}
flush();
}
public void flush() {
try {
outputStream.flush();
} catch (IOException e) {
errorCode = 5;
}
}
}