A problem when creating the socket - android

I've a android app which try to connect to server. But there is a problem when I create a socket. the application hang when it try implement the following line:
Socket socket= null;
socket = new Socket("192.168.0.15", 6565);
note that I have added this permission:
<uses-permission android:name="android.permission.INTERNET" />
also I used the debug but it hang when it reach to creating socket line and I've got this detail about the error:
java.net.SocketTimeoutException: Socket is not connected id=829731319824
and I am sure that port is not bound.
I appreciate your time.

Your connection probably cannot be established or is taking some time to be established.
Operations on java.net.Socket are blocking that's why your application appears to be hung. To avoid "hanging" the UI, you should probably try to establish the connection using another thread so your UI thread won't block and will remain responsive.

Obviously your connection cannot be established and the problem lies not within your code but the network setup. To avoid your app to hang, make sure you catch the SocketTimeoutException to be able to show an error message to the user along with some buttons to, for instance, try again or cancel the connection.

Related

Nearby Connections no ConnectionResponseCallback

I'm using Nearby Connections API in Android. It's working fine except cases where there is a sudden disconnections.
The client again succeed in finding the endpoint, using the discovery process, yet when he uses sendConnectionRequest() Connections.ConnectionResponseCallback never called no matter if I restart the app both on the client and on the endpoint. Only when I restart both devices the connection start to work again.
I have 20+ devices on the client side so there might be connection between the two things.
Any help on issue or where to start debugging the issue would be great.
For making a connection in Nearby Connection API, the client don't just sends connection request, but Host also has to accept it-
Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId, myPayload, this);
or reject it-
Nearby.Connections.rejectConnectionRequest(mGoogleApiClient, remoteEndpointId);
try this, and in your connection response callback have conditions to do stuff
if(status.isSuccess()){
// Successful connection
} else {
// Failed connection
}
Hope it helped
You need to properly disconnect the connection when needed with;
Nearby.Connections.disconnectFromEndpoint(mGoogleApiClient, remoteEndpointId);
or;
Nearby.Connections.stopAllEndpoints(mGoogleApiClient);
https://developers.google.com/nearby/connections/android/manage-connections

Android bluetooth socket timeout

Maybe I miss something, but How can I change the timeout of BluetoothSocket.connect() ?
Thanks you
Anthony
You can't change timeout of BluetoothSocket.connect(). As documentation:
This method will block until a connection is made or the connection
fails. If this method returns without an exception then this socket is
now connected.
A workaround.
Ex: timeout 5s.
Using CountDownTimer to check if connect is complete(success or fail). After 5s, if connection is incomplete then use BluetoothSocket.close() to cancel.
As BluetoothSocket documentation:
close() can be used to abort this call from another thread.

when connect web service with ksoap2 i took this error java.net.SocketTimeoutException

i'm developing an android project.i used ksoap2 lib.And i'm writing axis2 web service
but i took this error on client(android)
java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 8080) after 600000ms: isConnected failed: ETIMEDOUT (Connection timed out)
Thanks..
java.net.SocketTimeoutException is a subclass of java.io.IOException. It signals that a timeout has occurred on a socket read or accept”. That means that this exception emerges when a blocking operation of the two, an accept or a read, is blocked for a certain amount of time, called the timeout. Let’s say that the socket is configured with a timeout of 5 seconds. If either the accept() or read() method, blocks for more than 5 seconds, a SocketTimeoutException is thrown, designating that a timeout has occurred.
To avoid that exception:-
If the server side application is under your control, you should try yo adjust the timeout barrier so that its more flexible on network delays. You should surely consider doing that especially when your server application will run in a remote machine. Other than that, you can check whatever causes delays in your network, a malfunctioning router etc. Another way to effectively handle it is to define a connection timeout and later handle it by using a try catch block....
e.g,
HttpUrlConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(time_in_millisec); //set the required timeout in milliseconds
It is important to note that after this exception is thrown. the socket remains valid, so you can retry the blocking call or do whatever you want with the valid socket (even reconnecting the server from catch block)
For more detail please go through the link http://examples.javacodegeeks.com/core-java/net/sockettimeoutexception/java-net-sockettimeoutexception-how-to-solve-sockettimeoutexception/
Source: www.simpalm.com

Dialog for incoming bluetooth request

In my application two devices are connected via bluetooth. In the background runs an own thread for the bluetooth connection. (Just like the example )
When one device wants to connect to another device i want a request dialog to be displayed on the second device.
So I guess that i have to modify the AcceptThread. The AcceptThread has to inform my mainThread (for example with a Handler).
In the AcceptThread I find this code:
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
Now here is my problem: this "blocking call" runs the whole time. How and when shall I inform my mainThread that another device wants to connect?
Definitely afterwards.
What you want is the result of the blocking call - of the .accept().
That is socket in your code.
Here is a quote from the Android BluetoothServerSocket documentation:
Then call accept() to listen for incoming connection requests. This
call will block until a connection is established, at which point, it
will return a BluetoothSocket to manage the connection. Once the
BluetoothSocket is acquired, it's a good idea to call close() on the
BluetoothServerSocket when it's no longer needed for accepting
connections. Closing the BluetoothServerSocket will not close the
returned BluetoothSocket.
So don't forget to do:
mmServerSocket.close()
After you receive a socket correctly - a BluetoothSocket actually -, you can choose what to do with it following the user's choice:
Should he go ahead, you just create the AsyncTask that reads from the socket until the AsyncTask is cancelled or an Exception occurs(on Bluetooth disconnect probably).
Should he decline, just cancel the socket
If you receive an Exception during the blocking call I would return to the main menu only a toast, saying something failed. But you can do a dialog (like retry?)

Socket close timing

I have what appears to be a timing problem between a client (Galaxy Nexus) and a custom server since upgrading from Ice Cream Sandwich to Jelly Bean. Here is the general flow:
Client opens socket, issues HTTP get to server
Server accepts, starts new thread, responds with HTTP header and 200 OK.
Server writes (binary) file to socket.
Client reads data from socket and saves to a file.
After server thread writes all data, it closes the socket, and terminates
This has worked well over the past several months prior to the Jelly Bean update. Since the update the binary transfer succeeds about 70% of the time. The remaining 30% fails
when 'serverSocket.getInputStream().read' returns a -1 indicating the end of stream has been reached. No data has been read, no error exceptions raised, nothing in logcat.
The possibility of a timing problem arises when I change the server behavior in step #5. The thread was closing the socket after the write with the observed problems. If I remove the socket close, terminate the thread after the write, and let the OS eventually close the socket then it seems to work all the time.
I used tcpdump and WireShark to look at the packets in both the successful and failed cases. In the failed case a socket is closed in a few milli-seconds while in the successful case the socket is closed is a quarter or more of a second. The net of this is that any delay we cause in the socket closing improves our chances for success.
If anyone has any suggestions with what we may be doing to cause this problem or suggestions on how to narrow down the problem please feel free to respond. I can add code samples if required.
It looks like that when the server ask for the connection close, the socket is immediatly closed. Maybe the default ocket linger's time has changed between version ???
Try setting the socket linger's time using:
socket.setSoLinger(boolean on, int timeout);
to have the server waiting some time before close channel if some data still waiting to be sent.
If this doesn't solve, you can change your flow above to:
...
4.Client reads data from socket and saves to a file.
5.Client send confirmation to server.
6.Server close connection.
--EDITED--
A gracefull way to achive the above without additional TCP data packets traveling for the closing confirmation is:
when server finish writing to the socket calls:
socket.shutdownOutput();
when client socket.read() returns -1, client calls:
socket.close();
This ensures that client is informed that all data has been sent, and sender will wait for the socket closure protocol to complete.

Categories

Resources