[英]java.lang.nullpointerexception in ServerSocket.accept()
我試圖通過網絡接收圖像,我按如下方式設置服務器
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()時顯示空指針異常; 線。 請幫忙我不知道出了什么問題。
如果您在該行獲得空指針異常,則它只能表示前一個:
ss = new ServerSocket(SERVERPORT );
聲明沒有正常返回。 這是ss
可能為null
的唯一可行方式。
(實際上,還有另外一種可能的解釋。由於ss
變量是包私有而不是final
,同一個包中的其他一些類可以進入並為其賦值null
。但我不認為這是合理的。為什么會有人寫代碼來做到這一點?)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.