简体   繁体   中英

Try to connect socket until server starts in AsyncTask

I want in AsyncTask my app to try to connect to server until the connection is done. If the server is running when i start the app, it works, but if i start tha app and then i start the server it says: 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;
        }
} 

UPDATE: _socket is created in onCreate method @Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_widget);

    if(_socket == null)
        _socket = new Socket();
-----------------------
}

This solved my problem: Does socket become unusable after connect() fails?

I had to create a new socket in the catch or finally block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM