我想创建套接字连接,但我遇到了一些问题。我必须在新线程中创建它,但我不能。如何在新线程中创建套接字
public class SocketManager {
private static SocketManager instance;
private BufferedReader in;
private PrintWriter out;
private Socket mSocket = null;
public static SocketManager me() {
if (instance == null) {
instance = new SocketManager();
}
return instance;
}
public void connection() {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
mSocket = new Socket(Constants.CHAT_SERVER_URL, 4444);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
public boolean isConnected() {
return mSocket.isConnected();
}
和
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView) findViewById(R.id.status);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
SocketManager.me().connection();
if (SocketManager.me().isConnected()) {
status.setText("Connected");
} else {
status.setText("Disconnected");
}
我有错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.net.Socket.isConnected()' on a null object reference
Becouse mSocket
在新线程创建,当我把它叫做它== NULL;如何在新线程中创建mSocket并使用它?
在我看来,'SocketManager.me()'返回 空值。您需要先添加空检查。 –
您需要等待套接字实际创建。你可以把Thread.sleep(1000)调用connection()和isConnected()来测试它吗? – ilj
我可以添加检查null,但它没有意义,因为我不需要mSocket == null,我nedd mSocket不为null – Pavel