Note that there are some explanatory texts on larger screens.

plurals
  1. POReconnecting to an Android Socket in order to wait for Server
    text
    copied!<p>So I have TCP server in Windows that is programmed in C++ and a client in JAVA, Android 4.0.4. </p> <p>In Android, I connect like this:</p> <pre><code>public boolean sendConnectRequest() { while (isSocketConnected == false) { try { if(comSocket == null) comSocket = new Socket("192.168.0.1",1531); isSocketConnected = comSocket.isConnected(); if (isSocketConnected) { out = comSocket.getOutputStream(); in = comSocket.getInputStream(); } else comSocket.close(); } catch (IOException ex) { Log.e("TCP Error", ex.getLocalizedMessage()); } } return true; } </code></pre> <p>I typically have no problems with this code on the first connection to the server.</p> <p>When i disconnect from the server, I call this:</p> <pre><code>public void closeConnection() { if (comSocket != null) { try { comSocket.close(); isSocketConnected = false; if (out != null) out.close(); if (in != null) out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>So here is the problem... I hit the home button on the smartphone, which places the program in pause. I start the program again and it calls the resume function in activity, which in turn starts the process toward reconnection. The connection is attempted and i get no errors. However, my Windows server records no connection. In Windows, I know that I am still blocked at:</p> <pre><code>SOCKET connectionSocket = accept(tcpNetworkData-&gt;socket, (struct sockaddr*)&amp;from, &amp;fromlen); </code></pre> <p>I believe this is normal. When I am in debug mode on the Android side, I notice that it returns immediately from the line: comSocket = new Socket("192.168.0.1",1531); This should indicate to me that a connection is made. </p> <p>If you follow me so far... I should also say that if I shut the server down, the client resets by closing the connection and opening a new one. This time the comSocket = new Socket("192.168.0.1",1531) does not block as it should and the execution keeps going. This is obviously wrong. I think it is a resource release problem but why? With Winsock you can solve this problem with this line of code:</p> <pre><code>int so_reuseaddr = TRUE; setsockopt(networkData-&gt;socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&amp;so_reuseaddr,sizeof(so_reuseaddr)); </code></pre> <p>Can you do something similar with Android or do you have to? Thank you for your help!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload