我想在AsyncTask我的应用程序尝试连接到服务器,直到连接完成。如果服务器在我启动应用程序时正在运行,它可以运行,但是如果我启动应用程序然后我启动服务器它会说:java.io.IOException:fcntl failed:EBADF(Bad file number)
public class FetchData extends AsyncTask {
BufferedReader in;
InetSocketAddress socketAddress;
@Override
protected Object doInBackground(Object[] params) {
socketAddress = new InetSocketAddress("192.168.1.158", 9999);
while(!_socket.isConnected()) {
try {
_socket.connect(socketAddress);
Log.d("socket_status", "Socket is connected!");
break;
} catch (IOException e) {
Log.d("socket_status", e.toString());
e.printStackTrace();
}
}
return null;
}
}
更新:_socket是在onCreate方法@Override
中创建的protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_widget);
if(_socket == null)
_socket = new Socket();
-----------------------
}
答案 0 :(得分:0)
这解决了我的问题:Does socket become unusable after connect() fails?
我必须在catch或finally块中创建一个新套接字。