0

我正在尝试通过网络接收图像,我设置了一个服务器,如下所示

 public class IServerActivity extends Activity {
   ServerSocket ss = null;
   Bitmap bp ;
   Thread myCommsThread = null;
   protected static final int MSG_ID = 0x1337;
   public static final int SERVERPORT = 6000;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      //TextView tv = (TextView) findViewById(R.id.TextView01);       
      this.myCommsThread = new Thread(new CommsThread());
      this.myCommsThread.start();
   }

   @Override
   protected void onStop() {
      super.onStop();
      try {
         // make sure you close the socket upon exiting
         ss.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   Handler myUpdateHandler = new Handler() {
      public void handleMessage(Message msg) {
         switch (msg.what) {
         case MSG_ID:
            ImageView iv = (ImageView) findViewById(R.id.imageView01);
            iv.setImageBitmap(bp);;
            break;
         default:
            break;
         }
         super.handleMessage(msg);
      }
   };
   class CommsThread implements Runnable {
      public void run() {
         Socket s = null;
         try {
            ss = new ServerSocket(SERVERPORT );
         } catch (IOException e) {
            e.printStackTrace();
         }
         while (!Thread.currentThread().isInterrupted()) {
            Message m = new Message();
            m.what = MSG_ID;
            try {
               if (s == null)
                  s = ss.accept();
               bp= BitmapFactory.decodeStream(s.getInputStream());   
               myUpdateHandler.sendMessage(m);
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

但它在运行时显示错误

java.lang.NullPointerException 
E/AndroidRuntime(3047):atExample.IServer.IServerActivity$CommsThread.run(IServerActivity.java:68)

它在s=ss.accept();处显示空指针异常;线。请帮助我不知道出了什么问题。

4

1 回答 1

2

如果您在该行收到空指针异常,则只能表示较早的:

ss = new ServerSocket(SERVERPORT );

语句没有正常返回。这是唯一可行的方法。ssnull


(实际上,还有另一种可能的解释。由于ss变量是 package private 而不是final,同一包中的其他一些类可以访问并分配null给它。但我认为这不合理。为什么有人要编写代码去做?)

于 2012-07-09T06:54:11.983 回答