0

I'm writing an Android app that connects to an authentication server to retrieve the IP address and port of another Android device running a separate server program. The authentication server sends the correct connection information when the request is sent. The problem is when the client device attempts to connect to the Android server. The client gets the correct information and closes the previous connections successfully, but hangs when it attempts to create the new connections. No exceptions are thrown, but the UI is unresponsive and the device eventually says the app isn't responding. I have an emulator acting as the client device and an actual phone acting as the server.

Here is the part of the client code that it gets stuck on:

Log.i("Socket", "About to open a new socket");
socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
Log.i("Socket", "New socket created and registered");

ip is a String containing the IP address of the server. port is the port number of the server. I have the two calls to Log.i() to find where the program hangs. The first call executes, but the second doesn't. Is there any reason that this code segment would cause the app to freeze?

I can post more of my code if needed, but I'm pretty sure the problem is in the segment provided above.

1 Answers1

0

Two possibilities.

  1. The connect() call is in the middle of timing out, which takes around a minute depending on the platform. That basically means the target is inaccessible. You might want to review why that is. If you're not in control of what targets this code will connect to, you should put the channel into non-blocking mode, first, then connect, then register the channel for OP_CONNECT. If you go down this path, there is more to it, which I will add if requested.

  2. You have a Selector running in a different thread, and it is presently blocked in select (), which will block you from calling register(). The solution in this case is to wakeup the selector before calling register(), and make sure the selector thread copes correctly with a zero return from select().

user207421
  • 305,947
  • 44
  • 307
  • 483
  • The Selector is in the same thread as the connection, so it's not that. What are some possible reasons call to connect() is timing out? I have the code for the target device if that helps. – jakeprogrammer May 28 '13 at 11:30
  • I went back to the connection code and added more Log.i() statements, and changed the opening and connection to different lines. It's definitely hanging when on connect() – jakeprogrammer May 28 '13 at 12:09
  • So case (1) applies. The device or the intermediate network isn't responding (even though a route exists), – user207421 May 28 '13 at 22:07
  • Do you have any suggestions about how I can find the problem? – jakeprogrammer May 28 '13 at 22:17