Server
public void run () {
Socket serversocket = new ServerSocket(port);
while(true) {
new Thread(new ServerThread(serverSocket.accept())).start();
}
}
//serverSocket.close(); etc
ServerThread
public void run() {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String input;
while(true) {
input = in.readLine();
new Thread(new RequestThread(clientSocket, input)).start();
}
}
//close sockets etc in.close() clientSocket.close();
Request Thread
public void run() {
//input was passed from constructor
String output = new SomeProtocol(input);
if(output == null)
break;
//true for auto flush
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(output);
}//closing out seems to also close the socket, so opted to not to close it, maybe this is the one giving me trouble?
Monitor
public class ServerMonitor implements Runnable{
private ServerThread server;
private LoggingClass log = LoggingClass .getInstance();
private int heartbeat = 0;
public ServerMonitor(ServerThread server) {
this.server = server;
}
public boolean checkFile() {
File file = new File("cmd//in//shutdown.txt");
return file.exists();
}
public void run() {
log.logToFile("Server monitor running");
while (true) {
incHeartbeat();
if (checkFile()) {
log.logToFile("Shutting down server");
break;
}
writeStatus();
this.delay(5000);
}
log.logToFile("Server monitor stopped");
}
public void delay(long delay) {
try {
wait(delay);
} catch (InterruptedException e) {
log.logToFile("Monitor sleep error");
e.printStackTrace();
}
}
public void writeStatus() {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(
"sys//status//status.txt"));
out.write("Start date:" + log.getStartDate());
out.newLine();
out.write("Current date:" + log.getTimestamp("yyyy-MMM-dd k:mm:ss"));
out.newLine();
out.write("Heartbeat:" + getHeartbeat());
out.newLine();
out.write("Cimd in:" + log.getCimdIn());
out.newLine();
out.write("Cimd out:" + log.getCimdOut());
out.newLine();
out.write("Keep alive:" + log.getCimdKeepAlive());
out.newLine();
out.write("HTTP in:" + log.getNumHTTPIn());
out.newLine();
out.write("HTTP out:" + log.getNumHTTPOut());
out.newLine();
out.close();
} catch (Exception e) {
log.logToFile("Write status error");
e.printStackTrace();
}
}
public int getHeartbeat() {
return heartbeat;
}
public synchronized void incHeartbeat() {
heartbeat++;
}
}
This is the rough skeleton of my app. I'm having trouble since sometimes it just stops without any errors. I suspect that it might be because of the sockets but I'm not quite sure so anyone of you guys got any ideas? thanks.
Added my class that monitors the server threads
>How do I know that it doesn't work
Heartbeat doesn't increment anymore