I work on application which constantly sends some data acquired from device to server API. And I have a service working all the time in background and collecting data and then a network thread in this service which is responsible for establishing connection with server and sending data.
The problem I have is that although I acquire Wake and WiFi locks on service startup, at some point when device is on 3g network with poor connection it seems that socket write method just hangs: I see this from logs I output after each operation
Network thread is very simple and may be described as
while(true) {
if(!connectedToServer) {
connectToServer();
}
acquireData();
sendData();
}
And sendData is very simple - it writes data to socket output stream. From what I see in logs it seems that OutputStream.write() call just blocks for indefinite time on poor connection.
Did anyone experience similar problems?
Thanks,
Related
I have an Android app that creates a MulticastSocket, joins a MC group and receives messages from another machine on the local wifi network.
MulticastSocket socket = new MulticastSocket(null); // Create an unbound socket.
socket.setSoTimeout(LISTEN_TIMEOUT_MILLIS);
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(listenPort)); // Bind to the configured multicast port
final WifiManager.MulticastLock lock = wifiManager.createMulticastLock("my_lock");
lock.acquire();
socket.setNetworkInterface(networkInterface);
socket.joinGroup(multicastGroup);
while (true) {
socket.receive(packet);
// Do something with the packet
// Handle timeout etc.
// Handle change of network interface by leaving group, setting netIntf and joining group again.
}
socket.leaveGroup(multicastGroup);
socket.close();
lock.release();
Works well on most Android devices (Huawei, Samsung), but on some (Pixel3), if the WiFi on the device is switched off and then back on again, while the app sees the Wifi connection come live, it can take up to 14 mins (it is extremely variable) before the MC messages start being received again.
Even throwing away the Socket and creating a fresh MCSocket doesn't alleviate the delay.
But it has to be some state that is held within the JVM, because a restart of the app causes it to connect immediately.
It feels like there is some lease that is being held for the MC connection that is only being renewed on a clock cycle.
So my questions are:
What is causing the MC messages to not flow immediately after the
WiFi connection comes back up and a new MCSocket is created to
listen to it.
What can I do to ensure timely resumption of the message flow?
I notice you've updated your question to include WifiManager.MulticastLock
I wonder if you are you reacquiring the lock when the Wifi connection comes back, some posts here on SO imply this is necessary.
I note the comment on the following post:
Re: https://stackoverflow.com/a/4002084/1015289
it turns out that your multicast lock is destroyed when the connectivity goes away (the long delay was me rewriting my code three times before I figured this out). So, you have to reacquire the lock every time the connection comes back
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?)
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.
I'm currently working on a Project in my University which is an Android-App which is supposed to deliver data to a Server.
In order to do that I require a more or less consistent connection to the server via XMPP. It is not really important that the connection is there 100% of the time, but it because the system is supposed to be more or less invisible to the user, user-interaction is supposed to be minimal.
Both the server and the client are xmpp-clients. I use jabber.org as the xmpp server.
I have an Android-Service that is establishing the connection to server and delivers data and this works fine.
Now I tried to make the Service reconnect when connection is lost or is Changed from Wifi to GSM. I wanted to try to make this work with a broadcastreceiver listening to NETWORK_STATE_CHANGED_ACTION. But I did not even get this far.
This is the problem: I tried running the app and then just disabling my wifi. My Phone than automatically switches to GSM and I lose my connection (which I anticipated). But when I try to reconnect manually (e.g. restarting the service) I get errors from the Server. Also my status is still "available". From that moment on it takes way too long until I can connect again.
06-29 18:12:14.888: WARN/System.err(14246): resource-constraint(500)
06-29 18:12:14.890: WARN/System.err(14246): at org.jivesoftware.smack.NonSASLAuthentication.authenticate(NonSASLAuthentication.java:110)
06-29 18:12:14.890: WARN/System.err(14246): at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:404)
06-29 18:12:14.890: WARN/System.err(14246): at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
....
I am actually connected to the xmpp Server but it does not deliver my message:
06-29 18:12:14.882: INFO/System.out(14246): 06:12:14 nachm. RCV (1079704816): <iq type='error' id='7rhk4-70'><error code='500' type='wait'><resource-constraint xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/></error></iq>
Sometimes I don't get the error, but still no messages are being delivered.
So I think that the server is not allowing me to connect, because I did not disconnect before trying to reconnect. Which I find strange because I thought you could even connect from multiple clients to one account.
I'm posting some code that I think might be relevant:
public void connectToServer() throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration(
serverADD, port,
service);
connection = new XMPPConnection(config);
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(user_JID,password);
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("available");
presence.setPriority(24);
presence.setMode(Presence.Mode.available);
connection.sendPacket(presence);
}
this is how I send the messages:
public void sendMessage(String message, String recipient) throws XMPPException {
chat = connection.getChatManager().createChat(recipient, this);
chat.sendMessage(message);
}
Does anyone hava an idea how to solve this? I would even use "dirty" tricks as long as my message gets delivered to the server.
By the way: The senders and the recipients jids are always the same (after initial setup). Just in case anyone thinks that could matter.
Deadlock during Smack disconnect
As Airsource Ltd. mentioned in his comment: Smack is suffering from an deadlock in disconnect() which is loged as SMACK-278. I have made a commit that fixes this in my smack fork.
Android reconnection handling
For the network fallover, have a look at the GTalkSMS receiver. It will issue a ACTION_NETWORK_CHANGED intent, with the boolean extras "available" and "fallover". Your service should "stop" the connection when "available=false" and "fallover=false". How you "stop" the connection is up to you. Sometimes the disconnect() takes very long even with the fix for SMACK-278, this is why we do the disconnect in an thread that will abort after x seconds and then creates a new Connection instance. We reconnect then when the intent with "available=true" is received.
You will find other examples in the GTalkSMS source. I have the app permanently running and it achieves a stable, but not 100% available connection (because of WLAN <-> GSM switches).
I have a simple app that periodically sends HTTP_GET requests to a server. When sending requests over 3G, I noticed that the requests sometimes time out (and the server-side logging shows that it NEVER receives the request either).
After trying out different combinations I found one consistant pattern when this problem occures (it times out after every 5-15 successful requests).
- TelephonyRegistry: notifyDataConnection() state=2isDataConnectivityPossible()true, reason=null
- TelephonyRegistry: broadcastDataConnectionStateChanged() state=CONNECTEDtypes=default supl, interfaceName=rmnet0
- NetworkLocationProvider: onDataConnectionStateChanged 3
According to Google, NetworkLocationProvider is changed to 'DATA_SUSPENDED', which implies "connection is up, but IP traffic is temporarily unavailable". (see TelephonyManager). On the situations where HTTP_GET requests succeeds, the state is changed to '8'. My app doesn't use the location manage and I've shut down every other non-critical app from running!
I want to know:
What is the cause of this issue? Why does the connection status go to DATA_SUSPENDED?
Is it possible to avoid/overcome this problem?
Any help/insight into this is much appreciated! Thanks in advance!
I have the same problem with my app running on an Huawei IDEOS X3 with Android 2.3.5. The app sends data each minute to a server using HttpClient.
Using logcat I can see that the data connection is lost and then reestablished after a short while. Previously my app stopped working since it tried to send data without a connection causing an exception which was not properly handed.
I don't know the reason for the intermittently dropped data connection but I now handle the situation by checking if there is a data connection prior to sending the data. In my case it does not matter if some data is never sent. If it was important to avoid data loss, I could buffer the data and send it once the connection was back.
public Boolean isDataConnection() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return tm.getDataState() == TelephonyManager.DATA_CONNECTED;
}