programmieren-projekt/src/AsyncSocket.java

80 lines
1.9 KiB
Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
public class AsyncSocket {
private Socket socket;
private Thread checkerThread;
private AsyncSocketListener handler;
private boolean shouldStop = false;
private BufferedReader in;
private PrintWriter out;
public AsyncSocket(Socket socket, AsyncSocketListener handler) throws IOException {
this.socket = socket;
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.out = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()));
this.handler = handler;
this.checkerThread = new Thread(() -> {
while (!this.shouldStop) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
if (!this.in.ready()) continue;
if (this.handler == null) continue;
String message = this.in.readLine();
if (message.length() <= 0) continue;
// TODO: remove \r\n
this.handler.receive(message);
} catch (IOException e) {
e.printStackTrace();
}
}
});
this.checkerThread.start();
}
public void setHandler(AsyncSocketListener handler) {
this.handler = handler;
}
public void send(SocketPackage socketPackage) {
this.sendLine(socketPackage.toString());
}
public void send(String packageName) {
this.send(packageName, "");
}
public void send(String packageName, String packageContent) {
if (packageContent.length() > 0) {
packageContent = " " + packageContent;
}
this.sendLine(packageName + packageContent);
}
public void sendLine(String message) {
this.out.print(message + "\r\n");
}
public void close() {
this.shouldStop = true;
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}