我编写了一个客户端,该客户端在与主线程不同的线程中使用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.objectInStreamClient类中创建:

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


谁能告诉我是什么引起了问题,请问如何解决?

最佳答案

如果该try后没有紧随其后的catch (EOFException exc)关闭套接字并退出循环,则您的代码不正确。

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

关于java - objectinputstream.readobject()行:不可用[局部变量不可用],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16290843/

10-11 23:18