1

I have written a client that reads TCP messages using an ObjectInputStream in a separate thread from the main thread. I am using Eclipse and although no exception is thrown in the console, at random times the debug window will open and show the following error in what I assume is the Thread stack trace:

Thread[Thread-5](Suspended (exception ThreadDeath))
  objectinputstream.readobject() line: not available [local variables unavailable]
  ReceiveRunnable.run()line:25
  Thread.run()line:not available

This the code that the exception points to:

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 is created in the Client class:

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();
    }
}

Can anyone tell me what is causing the problem and how I might resolve please?

4

1 回答 1

1

如果try后面没有catch (EOFException exc)关闭套接字并跳出循环的 a,则您的代码不正确。

您应该始终为同一个套接字创建ObjectOutputStream之前ObjectInputStream,而不是之后,否则您可能会出现死锁。

于 2013-04-30T01:41:17.950 回答