我有2个按钮btn_openport和btn_closeport,其代码如下: btn_openport打开套接字并允许新连接:正常运行 btn_closeport在asynctask中在后台调用以下方法:
private static class closePort extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
Boolean closestatus = new OpenClosePort(port).closePort();
......rest of code
}
class openclose {
private Socket socket = null;
private ServerSocket server = null;
private static final String TAG = "ports";
private int port;
void openPort() {
try {
server = new ServerSocket(port);
socket = server.accept();
} catch () {
}
..........
}
Boolean closePort() {
Log.e(TAG + "/closePort", ">>> Closing Port : " + this.port);
try {
socket.close();
return true;
} catch (Exception e) {
Log.e(TAG + "/closePort", "Error closing port: ", e);
return false;
}
}
}
但是,当执行此用于关闭端口的代码时,尽管客户端已连接到套接字,但我却收到 NullPointerException 。
我该如何解决?
错误::
11-05 12:06:35.938 533-533/com.app.fi E/MyActivity/closePort: >>> Closing Port : 5556
11-05 12:06:35.941 533-533/com.app.fi E/MyActivity/closePort: Error closing port:
11-05 14:18:55.102 7460-8810/com.app.fi E/MyActivity/closePort: >>> Closing Port : 5556
11-05 14:18:55.104 7460-8810/com.app.fi E/MyActivity/closePort: Error closing port:
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.net.Socket.close()' on a null object reference
at com.app.fi.OpenClosePort.closePort(OpenClosePort.java:54)
at com.app.fi.MainActivity$closePort.doInBackground(MainActivity.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
11-05 14:18:55.109 7460-8810/com.app.fi W/checkPortStatus: Printing Socket value : Socket[address=localhost/127.0.0.1,port=5556,localPort=45524]
答案 0 :(得分:0)
为什么要创建一个用于关闭端口的新对象?在这一行
new OpenClosePort(port).closePort();
尝试创建OpenClosePort
类的对象,并在关闭端口时使用相同的对象。