ejabberd connection using Smack in android giving connection timed out error - android

Hello we have downloaded the ejabberd from this. domain is localhost and we have set the xmppDomain as my computer's ip address. I have used the following code for connection
public static final String XMPP_DOMAIN = "localhost";
public static final String XMPP_HOST = "10.0.2.2";//kept for emaulator
//public static final String XMPP_HOST = "192.168.1.152"; //ip of my pc
public static final int XMPP_PORT = 5222;
public static final String XMPP_RESOURCE = "xmppdemo";
public static final boolean XMPP_DEBUG = true;
private void initialiseConnection() throws IOException, InterruptedException, XMPPException, SmackException {
InetAddress addr = InetAddress.getByName(Constants.XMPP_HOST);
DomainBareJid serviceName = JidCreate.domainBareFrom(Constants.XMPP_DOMAIN);
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration
.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setXmppDomain(serviceName);
config.setHostAddress(addr);
config.setPort(Constants.XMPP_PORT);
config.setDebuggerEnabled(Constants.XMPP_DEBUG);
config.setResource(Constants.XMPP_RESOURCE);
connection = new XMPPTCPConnection(config.build());
connection.addConnectionListener(mConnectionListener);
connection.addAsyncStanzaListener(mStanzaListener, new StanzaFilter() {
#Override
public boolean accept(Stanza stanza) {
//You can also return only presence packets, since we are only filtering presences
return true;
}
});
Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
roster = Roster.getInstanceFor(connection);
roster.addRosterListener(mRoasterListener);
}
public void connect() {
#SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
//There is no point in reconnecting an already established connection. So abort, if we do
if (connection.isConnected())
return false;
//We are currently in "connection" phase, so no requests should be made while we are connecting.
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(service, "connecting....", Toast.LENGTH_LONG).show();
}
});
if (debug) Log.d(TAG, "connecting....");
try {
connection.connect();
/**
* Set delivery receipt for every Message, so that we can confirm if message
* has been received on other end.
*
* #NOTE: This feature is not yet implemented in this example. Maybe, I'll add it later on.
* Feel free to pull request to add one.
*
* Read more about this: http://xmpp.org/extensions/xep-0184.html
**/
DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(connection);
dm.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt) {
}
// #Override
// public void onReceiptReceived(final String fromid,
// final String toid, final String msgid,
// final Stanza packet) {
//
// }
});
connected = true;
} catch (IOException e) {
service.onConnectionClosed();
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText(service, "IOException: ", Toast.LENGTH_SHORT).show();
}
});
if (debug) Log.e(TAG, "IOException: " + e.getMessage());
} catch (SmackException e) {
service.onConnectionClosed();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(service, "SMACKException: ", Toast.LENGTH_SHORT).show();
}
});
if (debug) Log.e(TAG, "SMACKException: " + e.getMessage());
} catch (XMPPException e) {
service.onConnectionClosed();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(service, "XMPPException: ", Toast.LENGTH_SHORT).show();
}
});
if (debug) Log.e(TAG, "XMPPException: " + e.getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
}
//Our "connection" phase is now complete. We can tell others to make requests from now on.
return isconnecting = false;
}
};
connectionThread.execute();
}
//Signup to server
public void Signup(SignupModel signupModel) {
XMPPError.Condition condition = null;
boolean errors = false;
String errorMessage = "";
String mUsername = signupModel.getUsername();
String mPassword = signupModel.getPassword();
boolean isPasswordValid = signupModel.checkPassword();
boolean areFieldsValid = signupModel.validateFields();
if (!isPasswordValid) {
errors = true;
errorMessage = Constants.SIGNUP_ERR_INVALIDPASS;
}
if (!areFieldsValid) {
errors = true;
errorMessage = Constants.SIGNUP_ERR_FIELDERR;
}
if (errors) {
service.onSignupFailed(errorMessage);
return;
}
new Thread(new Runnable() {
#Override
public void run() {
if (!connected && !isconnecting) connect();
}
}).start();
try {
// final AccountManager accountManager = AccountManager.getInstance(connection);
//
//
// accountManager.createAccount(Localpart.from(mUsername), mPassword);
AccountManager accountManager = AccountManager.getInstance(connection);
accountManager.sensitiveOperationOverInsecureConnection(true);
accountManager.createAccount(Localpart.from(mUsername), mPassword);
} catch (XMPPException | SmackException e) {
e.printStackTrace();
if (debug) Log.e(TAG, "Username: " + mUsername + ",Password: " + mPassword);
if (e instanceof XMPPException.XMPPErrorException) {
condition = ((XMPPException.XMPPErrorException) e).getXMPPError().getCondition();
}
if (condition == null) {
condition = XMPPError.Condition.internal_server_error;
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (XmppStringprepException e) {
e.printStackTrace();
}
if (condition == null) {
service.onSignupSuccess();
} else {
switch (condition) {
case conflict:
errorMessage = Constants.SIGNUP_ERR_CONFLICT;
break;
case internal_server_error:
errorMessage = Constants.SIGNUP_ERR_SERVER_ERR;
break;
default:
errorMessage = condition.toString();
break;
}
service.onSignupFailed(errorMessage);
}
}
//Login to server
public void login() {
try {
new Thread(new Runnable() {
#Override
public void run() {
if (!connected && !isconnecting) connect();
}
}).start();
if (debug) Log.i(TAG, "User " + userId + userPassword);
connection.login(userId, userPassword);
if (debug) Log.i(TAG, "Yey! We're logged in to the Xmpp server!");
service.onLoggedIn();
} catch (XMPPException | SmackException | IOException e) {
service.onLoginFailed();
if (debug) e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
When I run this code I an receiving the following exception (when tried to run from emulator)
SMACKException: The following addresses failed: '10.0.2.2:5222' failed because: /10.0.2.2 exception: java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 5222) from /192.168.232.2 (port 34922) after 30000ms
when tried to run from my device I kept HOST_NAME as my pc's ip address, but then I am receiving the following error
E/XMPPHandler: SMACKException: The following addresses failed: '192.168.1.152:5222' failed because: /192.168.1.152 exception: java.net.SocketTimeoutException: connect timed out
When I installed ejabberd on my pc then I received the following Access Control List page
.. Should I have to change something?? Or missing something?

I had this problem too. I don't know why, but ejabberd server on windows does not works properly. I tried installing server on linux and mac, and it's working correctly. But on windows version always gets SocketTimeoutException.

I had similar problem. I have openfire serevr installed in windows 10.
My code was
DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("desktop-urvfr83");
//DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("192.168.1.3");
InetAddress addr = InetAddress.getByName("192.168.1.3");
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("alir", "111111")
.setHostAddress(addr)
.setResource("phonn")
.setXmppDomain(xmppServiceDomain)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setPort(5222)
.build();
but it could not connect. When I disabled the firewall it worked correctly and connected.

Related

Cannot login , NullPointerException

I use aSmack and Openfire database to make a chat application. And now I'm stack because of NullPointerException which is occurred when I try to log in. Can somebody help me to solve this issue? I really don't know what to do.
Cause connection, loginUser, password are not null. This information is from my logcat.
org.jivesoftware.smack.tcp.XMPPTCPConnection#42c4fca0 connection
AJ1 loginUser
password54 password
My code:
public void connect() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
XMPPTCPConnectionConfiguration.Builder ConnectionConfiguration = XMPPTCPConnectionConfiguration.builder();
ConnectionConfiguration.setServiceName("lucky");
ConnectionConfiguration.setHost("192.168.100.5");
ConnectionConfiguration.setPort(5222);
ConnectionConfiguration.setSecurityMode(org.jivesoftware.smack.ConnectionConfiguration.SecurityMode.disabled);
ConnectionConfiguration.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(ConnectionConfiguration.build());
XMPPConnectionListener xmppConnectionListener = new XMPPConnectionListener();
connection.addConnectionListener(xmppConnectionListener);
try {
connection.connect(); //Error here
} catch (SmackException.ConnectionException e) {
// e.printStackTrace();
Log.e("Point_1","Exception " + e);
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
});
t.start();
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(XMPPConnection connection) {
if(!connection.isAuthenticated()){
login(); //Error here
Log.e("Point_login", "XMPPListener, login()");
}
connected = true;
Log.e("Point_login", "XMPPListener, connected()");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
loggedin = true;
Log.e("Point_login", "XMPPListener, authenticated");
}
#Override
public void connectionClosedOnError(Exception e) {
Log.e("Point_login", "XMPPListener, connectinClosedOnError " + e);
loggedin = false;
connected = false;
isChatCreated = false;
}
#Override
public void connectionClosed() {
loggedin = false;
connected = false;
isChatCreated = false;
Log.e("Point_login", "XMPPListener, connectionClosed");
}
#Override
public void reconnectingIn(int seconds) {
loggedin = false;
Log.e("Point_login", "XMPPListener, reconnectingIn");
}
#Override
public void reconnectionFailed(Exception e) {
loggedin = false;
connected = false;
isChatCreated = false;
Log.e("Point_login", "XMPPListener, reconnectionFailed");
}
#Override
public void reconnectionSuccessful() {
loggedin = false;
connected = true;
isChatCreated = false;
Log.e("Point_login", "XMPPListener, reconnectionSuccessful");
}
}
public void login(){
try{
Log.e("Point_login", String.valueOf(connection) + " connection");
Log.e("Point_login", String.valueOf(loginUser) + " loginUser");
Log.e("Point_login", String.valueOf(password) + " password");
connection.login(loginUser,password); //Error here
}catch(SmackException.NotConnectedException e){
Log.e("Login_1","Exception");
for(int i=0;i<=5;i++){
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
}
}catch(XMPPException | SmackException | IOException e){
e.printStackTrace();
Log.e("Login_1","2nd Exception");
}
}
My logcat:
E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2634
java.lang.NullPointerException
at org.jivesoftware.smack.util.stringencoder.Base64.encode(Base64.java:64)
at org.jivesoftware.smack.util.stringencoder.Base64.encode(Base64.java:60)
at org.jivesoftware.smack.util.stringencoder.Base64.encodeToString(Base64.java:42)
at org.jivesoftware.smack.sasl.SASLMechanism.authenticate(SASLMechanism.java:199)
at org.jivesoftware.smack.sasl.SASLMechanism.authenticate(SASLMechanism.java:169)
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:236)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.loginNonAnonymously(XMPPTCPConnection.java:365)
at org.jivesoftware.smack.AbstractXMPPConnection.login(AbstractXMPPConnection.java:452)
at org.jivesoftware.smack.AbstractXMPPConnection.login(AbstractXMPPConnection.java:427)
at com.lets.dothis.myapplication.XMPP.login(XMPP.java:180)
at com.lets.dothis.myapplication.XMPP$XMPPConnectionListener.connected(XMPP.java:206)
at org.jivesoftware.smack.AbstractXMPPConnection.callConnectionConnectedListener(AbstractXMPPConnection.java:1152)
at org.jivesoftware.smack.tcp.XMPPTCPConnection.connectInternal(XMPPTCPConnection.java:841)
at org.jivesoftware.smack.AbstractXMPPConnection.connect(AbstractXMPPConnection.java:360)
at com.lets.dothis.myapplication.XMPP$1.run(XMPP.java:150)
at java.lang.Thread.run(Thread.java:856)
Thank you.
In login() method pass "XMPPConnection" object which is "connection" , like login(connection)
then, IN.... connection.login(loginUser,password);
replace that line with
if(!connection.isAuthenticated())
login(connection, loginUser, passwordUser);
else connection.login(loginUser, passwordUser);
I hope it will work.
Please don't make conflict with two objects with same name
XMPPConnection & XMPPTCPConnection , for simplicity , just rename one.
referance
http://xmpp-tutorials.blogspot.com.br/
please have a try & let me know if there is still any exception. thanks

ReconnectionManager is not working correctly

I am using smack library to implement chat solution in android. It is making connection with openfire perfectly but reconnection is not working at all.
I have a lost a connection on a device, on connection receive it does not reconnect or call any callbacks of reconnect. Please suggest how we can reconnect to openfire using ReconnectManager.
private boolean openConnection(String account, String password) {
try {
if (null == xmppConnection || !xmppConnection.isAuthenticated()) {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setHost(Constants.XMPP_SERVER_DOMAIN);
config.setServiceName(Constants.XMPP_SERVER_DOMAIN);
config.setPort(Constants.XMPP_SERVER_PORT);
config.setUsernameAndPassword(account, password);
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setCompressionEnabled(true);
config.setDebuggerEnabled(true);
TLSUtils.acceptAllCertificates(config);
xmppConnection = new XMPPTCPConnection(config.build());
xmppConnection.setPacketReplyTimeout(10000);
ReconnectionManager.getInstanceFor(xmppConnection).enableAutomaticReconnection();
connectionListener = new XmppConnectionListener();
packetListener = new XmppPacketListener();
xmppConnection.addAsyncPacketListener(packetListener, new PacketFilter() {
#Override
public boolean accept(Stanza packet) {
return true;
}
});
xmppConnection.addConnectionListener(connectionListener);
xmppConnection.connect().login();
return true;
}
} catch (XMPPException xe) {
xe.printStackTrace();
xmppConnection = null;
} catch (IOException io) {
io.printStackTrace();
xmppConnection = null;
} catch (SmackException se) {
se.printStackTrace();
xmppConnection = null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
xmppConnection = null;
} catch (KeyManagementException e) {
e.printStackTrace();
xmppConnection = null;
}
return false;
}
XmppConnectionListener.java
public class XmppConnectionListener implements ConnectionListener {
private static final String TAG = "XmppConnectionListener";
#Override
public void reconnectionSuccessful() {
Log.d(TAG, "reconnectionSuccessful()");
}
#Override
public void reconnectionFailed(Exception arg0) {
Log.d(TAG, "reconnectionFailed()");
}
#Override
public void reconnectingIn(int arg0) {
Log.d(TAG, "reconnectingIn()");
}
#Override
public void connectionClosedOnError(Exception arg0) {
Log.d(TAG, "connectionClosedOnError()");
}
#Override
public void connected(XMPPConnection connection) {
Log.d(TAG, "connected()");
}
#Override
public void authenticated(XMPPConnection connection, boolean resumed) {
Log.d(TAG, "authenticated()");
}
#Override
public void connectionClosed() {
Log.d(TAG, "connectionClosed()");
}
}

xmpp: ConnectionClosedOn Error! Parser got END_DOCUMENT event

I'm trying too login to the android app that i have created whose authentication will be done using the username and password registered in ejabberd. The connection is successfully established but i'm not abe to login. It gives an error namely -
"ConnectionClosedOn Error! Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element"
The log is:
04-15 19:27:45.052 31421-31421/com.synergy.allie.ecm D/calling xmpp connect: started
04-15 19:27:45.052 31421-31749/com.synergy.allie.ecm D/Connect() Function: =>connecting....
04-15 19:27:45.072 31421-31421/com.synergy.allie.ecm D/LoginActivity: onServiceConnected
04-15 19:27:45.102 31421-31751/com.synergy.allie.ecm I/System.out: 07:27:45 PM SENT (0): http://etherx.jabber.org/streams' version='1.0' xml:lang='en'>
04-15 19:27:45.102 31421-31752/com.synergy.allie.ecm I/System.out: 07:27:45 PM RECV (0): http://etherx.jabber.org/streams' id='284868730' from='allen' version='1.0' xml:lang='en'>
04-15 19:27:45.102 31421-31752/com.synergy.allie.ecm I/System.out: 07:27:45 PM RECV (0): http://jabber.org/protocol/caps' hash='sha-1' node='http://www.process-one.net/en/ejabberd/' ver='SLr01mk3X636tk4sDXYXPXsNNcE='/>http://jabber.org/features/iq-register'/>PLAINDIGEST-MD5SCRAM-SHA-1
04-15 19:27:45.142 31421-31749/com.synergy.allie.ecm D/xmpp: Connected!
04-15 19:28:45.102 31421-31752/com.synergy.allie.ecm W/AbstractXMPPConnection: Connection closed with error
org.jivesoftware.smack.SmackException: Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.parsePackets(XMPPTCPConnection.java:1148)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader.access$200(XMPPTCPConnection.java:937)
at org.jivesoftware.smack.tcp.XMPPTCPConnection$PacketReader$1.run(XMPPTCPConnection.java:952)
at java.lang.Thread.run(Thread.java:856)
04-15 19:28:45.112 31421-31752/com.synergy.allie.ecm D/xmpp: ConnectionClosedOn Error! Parser got END_DOCUMENT event. This could happen e.g. if the server closed the connection without sending a closing stream element
public class MyXMPP
{
public static boolean connected = false;
public boolean loggedin = false;
public static boolean isconnecting = false;
public static boolean isToasted = true;
private boolean chat_created = false;
private String serverAddress;
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
Gson gson;
MyService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
public org.jivesoftware.smack.chat.Chat Mychat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
Boolean logon;
public MyXMPP(MyService context, String serverAdress, String logiUser,
String passwordser) {
this.serverAddress = serverAdress;
this.loginUser = logiUser;
this.passwordUser = passwordser;
this.context = context;
init();
}
public static MyXMPP getInstance(MyService context, String server,
String user, String pass) {
if (instance == null) {
instance = new MyXMPP(context, server, user, pass);
instanceCreated = true;
}
return instance;
}
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
gson = new Gson();
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serverAddress);
config.setHost("***.***.***.***");
config.setPort(5222);
config.setDebuggerEnabled(true);
XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
XMPPTCPConnection.setUseStreamManagementDefault(true);
connection = new XMPPTCPConnection(config.build());
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
connection.addConnectionListener(connectionListener);
}
public void disconnect() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connect(final String caller) {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected synchronized Boolean doInBackground(Void... arg0) {
if (connection.isConnected())
return false;
isconnecting = true;
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, caller + "Trying to establish a connection!", Toast.LENGTH_LONG).show();
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
DeliveryReceiptManager dm = DeliveryReceiptManager
.getInstanceFor(connection);
dm.setAutoReceiptMode(AutoReceiptMode.always);
dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
#Override
public void onReceiptReceived(final String fromid,
final String toid, final String msgid,
final Stanza packet) {
}
});
connected = true;
} catch (IOException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "IOException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "IOException: " + e.getMessage());
} catch (SmackException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "SMACKException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("(" + caller + ")", "SMACKException: " + e.getMessage());
} catch (XMPPException e) {
if (isToasted)
new Handler(Looper.getMainLooper())
.post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "(" + caller + ")" + "XMPPException: ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("connect(" + caller + ")",
"XMPPException: " + e.getMessage());
}
return isconnecting = false;
}
};
connectionThread.execute();
}
public void login()
{
try
{
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Praise Jesus! We're connected to the Xmpp server!");
logon=true;
}
catch (XMPPException | SmackException | IOException e)
{
logon=false;
e.printStackTrace();
}
catch (Exception e)
{
logon=false;
}
}
private class ChatManagerListenerImpl implements ChatManagerListener {
#Override
public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,
final boolean createdLocally) {
if (!createdLocally)
chat.addMessageListener(mMessageListener);
}
}
public void sendMessage(ChatMessage chatMessage) {
String body = gson.toJson(chatMessage);
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(chatMessage.receiver
+ "#" + context.getString(R.string.server),
mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(body);
message.setStanzaId(chatMessage.msgid);
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
} else {
login();
}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
} catch (Exception e) {
Log.e("xmpp.SendMessage()", "msg Not sent!" + e.getMessage());
}
}
public class XMPPConnectionListener implements ConnectionListener {
#Override
public void connected(final XMPPConnection connection) {
Log.d("xmpp", "Connected!");
connected = true;
if (!connection.isAuthenticated()) {
login();
}
}
#Override
public void connectionClosed() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "ConnectionCLosed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionCLosed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void connectionClosedOnError(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ConnectionClosedOn Error!!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ConnectionClosedOn Error! "+arg0.getMessage());
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
loggedin = false;
}
#Override
public void reconnectionFailed(Exception arg0) {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "ReconnectionFailed!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionFailed!");
connected = false;
chat_created = false;
loggedin = false;
}
#Override
public void reconnectionSuccessful() {
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "REConnected!",
Toast.LENGTH_SHORT).show();
}
});
Log.d("xmpp", "ReconnectionSuccessful");
connected = true;
chat_created = false;
loggedin = false;
}
#Override
public void authenticated(XMPPConnection arg0, boolean arg1) {
Log.d("xmpp", "Authenticated!");
loggedin = true;
ChatManager.getInstanceFor(connection).addChatListener(
mChatManagerListener);
chat_created = false;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
if (isToasted)
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(context, "Connected!",
Toast.LENGTH_SHORT).show();
}
});
}
}
private class MMessageListener implements ChatMessageListener {
public MMessageListener(Context contxt) {
}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat,
final Message message) {
Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"
+ message);
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
final ChatMessage chatMessage = gson.fromJson(
message.getBody(), ChatMessage.class);
processMessage(chatMessage);
}
}
private void processMessage(final ChatMessage chatMessage) {
chatMessage.isMine = false;
Chats.chatlist.add(chatMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Chats.chatAdapter.notifyDataSetChanged();
}
});
}
}
}
try this code
public void initConnection(String user, String pass) throws XMPPException {
// TODO Auto-generated method stub
String SERVER_HOST = "192.168.1.199";
int SERVER_PORT = 5222;
String SERVICE_NAME = "Allen";
try {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
XMPPTCPConnectionConfiguration.Builder connConfig = XMPPTCPConnectionConfiguration
.builder();
connConfig
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
connConfig.setUsernameAndPassword(user, pass);
connConfig.setServiceName(SERVICE_NAME);
connConfig.setHost(SERVER_HOST);
connConfig.setPort(SERVER_PORT).setCompressionEnabled(false);
connConfig.setDebuggerEnabled(true);
connConfig.setConnectTimeout(25000);
XMPPTCPConnectionConfiguration configuration = connConfig.build();
// XMPPTCPConnection.setUseStreamManagementDefault(true);
// XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
// XMPPTCPConnection.setReplyToUnknownIqDefault(true);
connection = new XMPPTCPConnection(configuration);
connection.setUseStreamManagement(true);
connection.setUseStreamManagementResumption(true);
connection.setReplyToUnknownIq(true);
connection.setPacketReplyTimeout(25000);
ReconnectionManager manager = ReconnectionManager.getInstanceFor(connection);
manager.setFixedDelay(15);
ReconnectionManager.setDefaultReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY);
manager.enableAutomaticReconnection();
try {
connection.connect();
connection.login();
//logIn();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

Android bluetooth socket .connect() error

here is my code:
Thread connectThread = new Thread(new Runnable() {
#Override
public void run() {
try {
boolean gotuuid = btDevices.getItem(position)
.fetchUuidsWithSdp();
if (gotuuid){
UUID uuid = btDevices.getItem(position).getUuids()[0]
.getUuid();
mbtSocket = btDevices.getItem(position)
.createRfcommSocketToServiceRecord(uuid);
mbtSocket.connect();
} else {
Log.e("ID22", "There is no uuid");
}
} catch (IOException ex) {
runOnUiThread(socketErrorRunnable);
try {
mbtSocket.close();
} catch (IOException e) {
// e.printStackTrace();
}
mbtSocket = null;
return;
} finally {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
}
});
}
}
});
connectThread.start();
}
When I try to use mbtSocket.connect();to connect to the bluetooth soccket it stops and throws socketErrorRunnable exception. Have you got any idea how to fix this? I searched about that but nothing works for me.
In case you have troubles here are some code from the official Android Bluetooth Chat example :
Server side :
public class BluetoothServer {
private final static String TAG = "BluetoothServer";
private final BluetoothServerSocket serverSocket;
// I would recommand defining a secure connexion so forget the unsecore UUID
private static final UUID MY_UUID_SECURE =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"); // choose another UUID go to a site that generates a random UUI ;-)
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); // choose another UUID go to a site that generates a random UUI ;-)
// BUT THIS WILL BE THE UUID YOU NEED TO CONNECT TO IN YOUR CLIENT APP -> createRfcommSocketToServiceRecord(UUID.fromString("0800200c9a66"));
// Name for the SDP record when creating server socket
private static final String NAME_SECURE = "BluetoothChatSecure";
private static final String NAME_INSECURE = "BluetoothChatInsecure";
public BluetoothServer(BluetoothAdapter adapter, boolean secure) {
try {
if (secure) {
this.serverSocket = adapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
MY_UUID_SECURE);
} else {
this.serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + (secure ? "secure" : "insecure") + "listen() failed", e);
}
}
public void asyncStartServer() {
new Thread(new Runnable() {
#Override
public void run() {
try {
final BluetoothSocket socket = serverSocket.accept(); // blocks/wait until your phone connects
// at this point, your phone is connected
final InputStream is = socket.getInputStream();
// and now start reading
} catch (IOException ioe) {
Log.getStackTraceString(ioe);
}
}
}).start();
}
}

How to retrieve packet in a VpnService

I have the following implementation of ToyVpnService which I got frome here
public class ToyVpnService extends VpnService implements Handler.Callback, Runnable {
private static final String TAG = "ToyVpnService";
private Handler mHandler;
private Thread mThread;
private ParcelFileDescriptor mInterface;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Stop the previous session by interrupting the thread.
if (mThread != null) {
mThread.interrupt();
}
// Start a new session by creating a new thread.
mThread = new Thread(this, "ToyVpnThread");
mThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
if (mThread != null) {
mThread.interrupt();
}
}
#Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public synchronized void run() {
Log.i(TAG, "running vpnService");
try {
runVpnConnection();
} catch (Exception e) {
e.printStackTrace();
//Log.e(TAG, "Got " + e.toString());
} finally {
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = null;
mHandler.sendEmptyMessage(R.string.disconnected);
Log.i(TAG, "Exiting");
}
}
private boolean runVpnConnection() throws Exception {
configure();
FileInputStream in = new FileInputStream(mInterface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(32767);
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
Log.i(TAG, "************new packet");
System.exit(-1);
while (packet.hasRemaining()) {
Log.i(TAG, "" + packet.get());
//System.out.print((char) packet.get());
}
packet.limit(length);
// tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
}
Thread.sleep(50);
}
}
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
Log.i(TAG, "****** INET ADDRESS ******");
Log.i(TAG, "address: " + inetAddress.getHostAddress());
Log.i(TAG, "hostname: " + inetAddress.getHostName());
Log.i(TAG, "address.toString(): " + inetAddress.getHostAddress().toString());
if (!inetAddress.isLoopbackAddress()) {
//IPAddresses.setText(inetAddress.getHostAddress().toString());
Log.i(TAG, "IS NOT LOOPBACK ADDRESS: " + inetAddress.getHostAddress().toString());
return inetAddress.getHostAddress().toString();
} else {
Log.i(TAG, "It is a loopback address");
}
}
}
} catch (SocketException ex) {
String LOG_TAG = null;
Log.e(LOG_TAG, ex.toString());
}
return null;
}
private void configure() throws Exception {
// If the old interface has exactly the same parameters, use it!
if (mInterface != null) {
Log.i(TAG, "Using the previous interface");
return;
}
// Configure a builder while parsing the parameters.
Builder builder = new Builder();
builder.setMtu(1500);
builder.addAddress(getLocalIpAddress(), 24);
try {
mInterface.close();
} catch (Exception e) {
// ignore
}
mInterface = builder.establish();
}
}
It seems to be receiving packets but I have no idea on how to read the data in the paclkets. the code seems to be incomplete (hence the tunnel.write(packet) that's commented out cause there isn't a variable tunnel). Is this the right way? or is there a better way of doing this?

Categories

Resources