【发布时间】:2009-11-04 04:13:06
【问题描述】:
服务器
public void run () {
Socket serversocket = new ServerSocket(port);
while(true) {
new Thread(new ServerThread(serverSocket.accept())).start();
}
}
//serverSocket.close(); etc
服务器线程
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();
请求线程
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?
监控
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++;
}
}
这是我的应用程序的粗略骨架。我遇到了麻烦,因为有时它只是停止而没有任何错误。我怀疑这可能是因为插座,但我不太确定,所以你们中的任何人有什么想法吗?谢谢。
添加了我的监控服务器线程的类
>How do I know that it doesn't work
心跳不再增加
【问题讨论】:
-
我不知道问题出在哪里,但我建议您添加一些日志记录以帮助您查看应用程序在关闭时正在执行的操作。
-
关机需要多长时间?
-
随机的,有时会持续几天,有时甚至不会持续一个小时
-
至少不是即时的。您还可以将一些分析器附加到您的应用程序并查看发生了什么。分析器可能会告诉您哪些资源导致了可能的死锁或堆栈溢出。看看 Java 6 附带的 jConsole(我认为是从 Java 5 开始)
-
服务器上的java是1.4.3(他们不会更新ffs)
标签: java multithreading sockets