我编写了一个客户端,它在与主线程分开的线程中使用ObjectInputStream
读取TCP消息。我正在使用Eclipse,虽然在控制台中没有抛出任何异常,但随机时间调试窗口将打开并在我假设的线程堆栈跟踪中显示以下错误:
Thread[Thread-5](Suspended (exception ThreadDeath))
objectinputstream.readobject() line: not available [local variables unavailable]
ReceiveRunnable.run()line:25
Thread.run()line:not available
这是异常指向的代码:
class ReceiveRunnable implements Runnable {
Object receivedObject;
public void run() {
while (true) {
try {
receivedObject = client.objectInStream.readObject(); //line 25
} catch (IOException e) {
// client.reconnectToServer();
// System.out.println("IO exception in run()");
// System.out.println(e);
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found exception in run()");
System.out.println(e);
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception in ReceiveRunnable.run()");
System.out.println(e.toString());
e.printStackTrace();
}
}
}
}
client.objectInStream
在Client
类中创建:
void connectToServer(){
try {
connected = false;
socket = new Socket(host, port);
System.out.println("<Connected> " + socket);
objectInStream = new ObjectInputStream(socket.getInputStream());
objectOutStream = new ObjectOutputStream(socket.getOutputStream());
receiveThread = new Thread(new ReceiveRunnable(this, "receive"));
receiveThread.start();
/* used to periodically ping the server*/
long delay = 0;
long period = 5000;
connTimer.schedule(clientCheckConnTimerTask, delay, period);
connected = true;
sendString("[conn]" + clientUUID);
} catch (IOException e) {
msgBox.set2LineOkMessage("Can not connect to server.", "");
msgBox.show();
}
}
有人能告诉我导致问题的原因以及我可以解决的问题吗?
答案 0 :(得分:1)
如果try
后面没有关闭套接字并突破循环的catch (EOFException exc)
,则代码不正确。
您应始终在ObjectOutputStream
之前为同一套接字创建ObjectInputStream
,而不是之后,否则您可能会遇到死锁。