While on Wifi, XMPPTCPConnection in our Android app is occasionally throwing "SocketException: Machine is not on the network" even though the phone does have net connection. When users turns off Wifi and turns it on again, the app is able to connect instantly.
When this exception occurs, the XMPPTCPConnection object is disconnected and set to NULL and created afresh before attempting reconnection. Yet it does not help. Below is the code snippet.
try {
if (null != connection)
connection.disconnect();
} catch (Exception e) {
}
connection = null;
XMPPTCPConnectionConfiguration connConfig = createConfiguration();
if (null != connConfig)
{
connection = new XMPPTCPConnection(connConfig);
try {
connection.connect();
} catch (StackOverflowError e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Please let me know how to fix this issue. Appreciate your help.
This is the stack trace.
org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '.com:5223' failed because java.net.SocketException: Machine is not on the network
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectUsingConfiguration(XMPPTCPConnection.java:596)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java:830)
at org.jivesoftware.smack.AbstractXMPPConnection.connect(AbstractXMPPConnection.java:360)
at com.sarkms.cclib.XMPPConnLib.connectToChatServer(XMPPConnLib.java:184)
at com.sarkms.cclib.XMPPConnHelper.connectToChatServer(XMPPConnHelper.java:331)
at com.sarkms.cclib.XMPPConnHelper.LoginToChatServer(XMPPConnHelper.java:383)
at com.sarkms.cclib.ConnChkRun.runConnectionCheck(ConnChkRun.java:83)
at com.sarkms.cclib.ops.Connection.runConnection(Connection.java:142)
at com.sarkms.cclib.MessageService$1.run(MessageService.java:39)
Related
I'm trying to have my android app to be able to send and receive xmpp message using smack but it does not work and the connect command does not return. I have seen several code example but Smack has new versions and the syntax has changed so I might be doing something wrong :
in my build.graddle file I use :
compile "org.igniterealtime.smack:smack-android-extensions:4.3.0"
compile "org.igniterealtime.smack:smack-tcp:4.3.0"
I'm trying to send a message from myaccount321#xabber.org to myaccount456#xabber.org
I'm trying to connect using hot-chilli.net (Idon't mind using some other server))
everything seems to go well until connection.connect() after which the script does not return without triggering any exception.
Please tell me what I'm doing wrong
TIA
public void sendxmpp(){
XMPPTCPConnectionConfiguration config = null;
try {
XMPPTCPConnectionConfiguration.Builder configbuilder = XMPPTCPConnectionConfiguration.builder();
configbuilder.setUsernameAndPassword("myaccount321","myaccount321pw");
DomainBareJid serviceName = JidCreate.domainBareFrom("hot-chilli.net");
configbuilder.setServiceName(serviceName);
configbuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
configbuilder.setHost("jabber.hot-chilli.net");
configbuilder.setPort(8222);
config=configbuilder.build();
AbstractXMPPConnection connection = new XMPPTCPConnection(config);
try {
connection.connect();
}
catch (SmackException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (XMPPException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
connection.login();
ChatManager chatManager = ChatManager.getInstanceFor(connection);
EntityBareJid jid = JidCreate.entityBareFrom("myaccount321pw#xabber.org");
Chat chat = chatManager.createChat(jid);
chat.sendMessage("Hello");
}
catch (Exception e) {
}
}
OK I got it, the connection process has to be done in its own thread.
I made android application that connects to remote server and send some data.
Remote server is Windows application.
Connection method:
private void ConnectToMonitor() {
try {
s = new Socket(SERVER_ADDRESS, TCP_SERVER_PORT);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This works perfectly if server is online. Application is sending data and server is receiving. But if server is offline android app. is blocked. My question is how to handle this? How to continue with application and avoid error even the server is down?
Remember to call this outside the UIThread.
Follow this tutorial. In android all connections need to be managed outside the UIThread, in the tutorial I linked you will find easy ways to post your results back to the UI (handlers, asynctasks...)
Of course we don't know if the problem is about the thread with just the given code, but it is the most usual error.
First remember to set the socket timeout :
mSocket.setSoTimeout(timeout); //in milliseconds
You can however specify different timeout for connection and for all other I/O operations through the socket:
private void connectToMonitor() {
try {
socket = new Socket();
InetAddress[] iNetAddress = InetAddress.getAllByName(SERVER_ADDRESS);
SocketAddress address = new InetSocketAddress(iNetAddress[0], TCP_SERVER_PORT);
socket.setSoTimeout(10000); //timeout for all other I/O operations, 10s for example
socket.connect(address, 20000); //timeout for attempting connection, 20 s
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Second, in Android, you should perform any network I/O in separate threads!
As an example, using regular Java Threads :
String threadName = getClass().getName() + "::connect";
new Thread(new Runnable() {
#Override
public void run() {
connectToMonitor();
}
}, threadName).start();
You can set A timeout for the socket. Use Socket.setSoTimeout method
socket.setSoTimeout(timesinmilis);
by using this your socket will throw a socket timout exception. You can catch that and do what you want
I am trying to connect a bluetooth device from the Android phone. In most cases, the connection is successful.
I am making the socket connection using the following code:
if (isUsingHtcTypeConnectionScheme) {
try {
if (LOG_ENABLED) Log.d(TAG,"connecting to SPP with createRfcommSocket");
Method m = mRemoteDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
tmpSocket = (BluetoothSocket)m.invoke(mRemoteDevice, 1); // may be from 1 to 3
} catch (java.lang.NoSuchMethodException e){
Log.e(TAG, "java.lang.NoSuchMethodException!!!", e);
} catch ( java.lang.IllegalAccessException e ){
Log.e(TAG, "java.lang.IllegalAccessException!!!", e);
} catch ( java.lang.reflect.InvocationTargetException e ){
Log.e(TAG, "java.lang.InvocationTargetException!!!", e);
}
}
if (tmpSocket == null) {
try {
if (LOG_ENABLED) Log.d(TAG,"connecting to SPP with createRfcommSocketToServiceRecord");
tmpSocket = mRemoteDevice.createRfcommSocketToServiceRecord(uuid); // Get a BluetoothSocket for a connection with the given BluetoothDevice
} catch (IOException e) {
Log.e(TAG, "socket create failed", e);
}
}
mBtSocket = tmpSocket;
try {
mBtSocket.connect();
} catch (IOException e) {
connectionFailed();
setState(STATE_IDLE);
return;
}
And if the other device's bluetooth is not on, it will throw the IOException in 2-3 seconds, this is the normal behavior.
But sometimes the connection takes 20-30 seconds and eventually failed, and the other device's bluetooth is on.
I am wondering why this happens, if the phone cannot connect to device, it should throw IOException in 2-3 seconds. But now is taking 20-30 seconds to throw the IOException. (And the other device is ready for connection actually)
I tested on several Android phones and also have this problem, so may not be related to specific phone.
Any ideas?
Thanks!
I have referenced the link:
Disconnect a bluetooth socket in Android
but still it doesn't work for me. always through an exception at BluetoothSocket::connect()
My case is that if User has paired and connected a remote bt device via the phone, how can I programmatically disconnect it??
I got a hunch that if I want the connection to be disconnected I should close the input, output stream then perform BluetoothSocket close. And I can't find anywhere to get the socket on the connected device. the API createRfcommSocketToServiceRecord is to create a socket. Thank you!
PS, the remote bt device is headset
follow the below procedure
if (mmSocket != null) { try { mmSocket.close(); } catch (Exception e) { Log.e("Exception", "while closing socket"+e.toString()); } mmSocket = null; }
if (mmOutStream != null) { try { mmOutStream.close(); } catch (Exception e) { Log.e("Exception", "while closing outstream"+e.toString()); } mmOutStream = null; }
if (mmInStream != null) { try { mmInStream.close(); } catch (Exception e) { Log.e("Exception", "while closing inputstream"+e.toString());} mmInStream = null; }
I'm trying to write a test app which connects to BlackBerry 655+ bluetooth headset. Basically what i want to do in this app is connect to the headset and catch button pressures on it. I think that could be done by reading the socket's inputstream. Anyway, i get some errors right when i try to connect to the socket. Here's the code:
BluetoothSocket tmp = null;
try {
tmp = mDevice.createRfcommSocketToServiceRecord(
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
} catch(IOException e) {}
mSocket = tmp;
mBtAdapter.cancelDiscovery();
try {
mSocket.connect(); // THIS ONE GIVES A "Service discovery failed" exception
} catch (IOException e1) {
Method m = null;
try {
m = mDevice.getClass().getMethod(
"createRfcommSocket", new Class[] {int.class});
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
tmp = (BluetoothSocket) m.invoke(mDevice, 1);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
mSocket = tmp;
try {
mSocket.connect(); // THIS ONE GIVES A "Connection refused" EXCEPTION
} catch (IOException e) {
e.printStackTrace();
}
}
What am i doing wrong? I already tried different ports in the m.invoke(mDevice, X) instruction but it always gives "Connection refused"
I worked with Bluetooth before but with python and Java ME so I understand the basics. I don't know much about the android API though.
Where did you get the UUID code from? That could be one of the reasons for the Service discovery failed.
Each bluetooth device may have several services each of them associated to one port (or channel). If you are running ubuntu try using the hci tools to know to which channel connect or which service to search for.
Here you have an official list with UUIDs from Bluetooth SIG. For Headset Profile the UUID is 0x1108, the UUID used by you it is Base Universally Unique Identifier and it is used for SDP.