crashtest/src/de/ctdo/crashtest/CommunicationRunner.java

77 lines
2.4 KiB
Java

package de.ctdo.crashtest;
import java.io.*;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class CommunicationRunner implements Runnable {
private Socket clientSocket = null;
private GuiControl control;
public CommunicationRunner(Socket clientSocket, GuiControl control) {
this.clientSocket = clientSocket;
this.control = control;
}
@Override
public void run() {
try {
clientSocket.setSoTimeout(5000);
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
System.out.println("got line: " + line);
runCommand(line);
output.close();
input.close();
System.out.println("Request processed: " + time + clientSocket.getRemoteSocketAddress());
} catch (SocketTimeoutException e) {
System.out.println("Socket Timeout, closing " + clientSocket.getRemoteSocketAddress());
} catch (IOException e) {
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void runCommand(String line) {
// must contain a ":"
// then split and switch on the command
int pos = line.indexOf(":");
if(pos > 0) {
String command = line.substring(0, pos).toLowerCase().trim();
String parameter = line.substring(pos+1, line.length()).trim();
if(command.equals("wall")) {
control.setWall(parameter);
} else if(command.equals("timerstart")) {
control.startTimer(Integer.parseInt(parameter));
} else if(command.equals("timerstop")) {
control.stopTimer();
} else if(command.equals("timerpause")) {
control.pauseTimer(Boolean.parseBoolean(parameter));
} else if(command.equals("setextra")) {
control.setExtra(parameter);
} else if(command == "reset") {
control.resetGame();
}
}
}
}