2

我真的很感谢我的程序的一些帮助

    Exception in thread "Thread-4" java.lang.NullPointerException
    at ServerConnect.replyChoice(BaseStaInstance.java:63)
    at ServerConnect.run(BaseStaInstance.java:45)
    at java.lang.Thread.run(Thread.java:619)

我的 ServerConnect 函数如下所示:-

class ServerConnect extends Thread {

 Socket skt;
 String sProcessId;
 ServerConnect scnt = null; 
 ObjectOutputStream myOutput;
 ObjectInputStream myInput;


 ServerConnect(){}
 ServerConnect(Socket connection, String sProcessNo) {
  this.skt = connection;
  this.sProcessId = sProcessNo;
 }

 public void run() {
  try {
   myInput = new ObjectInputStream(skt.getInputStream());
   ServerConnect scnt = new ServerConnect();

   while(true) {
    try{
     int ownTimeStamp = Global.iTimeStamp;

     Object buf = myInput.readObject();

     //if we got input, print it out and write a message back to the remote client...
     if(buf != null){
 LINE 45-->     **scnt.replyChoice(buf);**

     }

    }catch(ClassNotFoundException e) {
     e.printStackTrace();
    }
   }
  } catch(IOException e) {
   e.printStackTrace();
  }
 }

 void replyChoice(Object buf){


  try{
LINE 63 --> **myOutput = new ObjectOutputStream(skt.getOutputStream());**


  System.out.println("Server read:[ "+buf+" ]");
  myOutput.writeObject("got it");
  myOutput.flush();

  }catch(IOException e){
  e.printStackTrace();
  }
 }
}

它基本上是一个套接字编程和多线程应用程序。在不同的终端上执行它以便让客户端和服务器建立连接时,我执行我的代码。但它在两个终端上都抛出了上面的错误。它只是与我在错误的位置声明 myOutput 变量有关。有人可以帮帮我。从错误消息中,我在附加的代码中突出显示了第 63 行和第 45 行。

4

3 回答 3

4
  1. 删除默认构造函数
  2. 使您的实例字段(stk 和 sProrcessId)最终确定
  3. 查看您的编译器如何抱怨并解决这些问题

这些说明可帮助您将运行时错误(如 NPE)转换为编译时错误,这是您能做的最好的事情。注意:这个技巧是为了普遍使用。

于 2010-02-27T17:09:42.173 回答
2

您的对象正在使用第一个构造函数进行初始化,该构造函数不带参数。因此,skt永远不会被初始化,因此是null。当您调用时skt.getOutputStream(),它会抛出一个空指针异常,因为它不能取消引用skt

于 2010-02-27T16:54:07.333 回答
0
 ServerConnect(){}
 ServerConnect(Socket connection, String sProcessNo) {
  this.skt = connection;
  this.sProcessId = sProcessNo;
 }

你用什么构造函数?因为 skt 可能未初始化

//编辑:哦,我现在看到你使用了错误的构造函数

   ServerConnect scnt = new ServerConnect();

   ServerConnect scnt = new ServerConnect(skt,sProcessId);
于 2010-02-27T16:54:27.000 回答