[英]java.lang.nullpointerexception in ServerSocket.accept()
I am trying to receive images over a network, I set up a server as follows 我试图通过网络接收图像,我按如下方式设置服务器
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();
}
}
}
}
}
But it shows an error at runtime 但它在运行时显示错误
java.lang.NullPointerException
E/AndroidRuntime(3047):atExample.IServer.IServerActivity$CommsThread.run(IServerActivity.java:68)
It shows null pointer exception at s=ss.accept(); 它在s = ss.accept()时显示空指针异常; line.
线。 please help I don't know what is going wrong.
请帮忙我不知道出了什么问题。
If you are getting a null pointer exception at that line, it can only mean that the earlier: 如果您在该行获得空指针异常,则它只能表示前一个:
ss = new ServerSocket(SERVERPORT );
statement did not return normally. 声明没有正常返回。 That is the only plausible way that
ss
could be null
. 这是
ss
可能为null
的唯一可行方式。
(Actually, there is one other possible explanation. Since the ss
variable is package private and not final
, some other class in the same package could reach in and assign null
to it. But I wouldn't think that was plausible. Why would anyone write code to do that?) (实际上,还有另外一种可能的解释。由于
ss
变量是包私有而不是final
,同一个包中的其他一些类可以进入并为其赋值null
。但我不认为这是合理的。为什么会有人写代码来做到这一点?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.