Not created, no toast is performed

public class MainActivity extends AppCompatActivity { String ip; int port; Socket fromServer; SocketConnectionTask socketConnection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Bundle extras = getIntent().getExtras(); ip = extras.getString("ip"); port = extras.getInt("port"); socketConnection = new SocketConnectionTask(this); socketConnection.execute(ip, String.valueOf(port)); } } class SocketConnectionTask extends AsyncTask<String, Void, Boolean> { Context context; Socket fromServer; public SocketConnectionTask(Context context) { this.context = context; } @Override protected Boolean doInBackground(String... params) { InetAddress address; try { address = InetAddress.getByName(params[0]); } catch (UnknownHostException e) { return false; } try { fromServer = new Socket(address, Integer.parseInt(params[1])); //Тут не переходит на следующие брейкпоиты } catch (IOException e) { return false; //Этот } return true; // И этот } @Override protected void onPostExecute(Boolean aBoolean) { boolean b = aBoolean; Toast.makeText(context, String.valueOf(b), Toast.LENGTH_LONG).show(); } } 

The server is written in Java . There is also a Java client Java but for some reason it connects to it only on the local network.

  • Is there anything in logcat? - Aleks G
  • @AleksG not, empty - Herrgott
  • It feels like he can't connect and he has a huge timeout. 3 minutes waiting - nothing - Herrgott
  • @AleksG Put. logcat is silent. Put 2 breakpoints on catch and return true does not catch. So debugger doesn’t go beyond socket creation line - Herrgott
  • Breakpoint on the line where the socket is created. - Aleks G

1 answer 1

Based on the comments, the connection cannot be established, and Android tries to do this for a long time (90 seconds?). To solve this problem, you need to specify a timeout:

 fromServer = new Socket(); SocketAddress address = new InetSocketAddress(ip, port); fromServer.connect(address, timeout); 

With this code, it will try no more than 5 seconds.

  • There is no such method - Herrgott
  • To specify a timeout, use the setSoTimeout (int ms) method; but it cannot be applied before creating an object of class Socket. Therefore, I do not know how to specify a timeout - Herrgott
  • @Herrgott Hmm ... The Android version of the socket does not contain connect with three parameters (it is in Java). Now I will look. - Aleks G
  • fromServer = new Socket(); SocketAddress address1 = new InetSocketAddress(address, Integer.parseInt(params[1])); fromServer.connect(address1, 5000); - Herrgott
  • @Herrgott Aha, that’s what I came up with :) - corrected in response - Aleks G