I have created an android chat application using XMPP server (openfire) and smack lib. When open my application i get connect =>connecting than a Oncreat SMACK exception appears. Which means that i can't establish a connexion with the server my code looks right but i cant figure out where is the probleme
here is the code
public class MyXMPP {
public static ArrayList<HashMap<String, String>> usersList=new ArrayList<HashMap<String, String>>();
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 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;
}
public org.jivesoftware.smack.chat.Chat Mychat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
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("farah-pc");
config.setHost("farah-pc");
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 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 + "=>connecting....", 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) {
}
});
Toast.makeText( context,"cava", Toast.LENGTH_SHORT).show();
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", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
// SmackException.ConnectionException.getFailedAddresses() ;
//HostAddress.getException();
Toast.makeText( context,"alaaach", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
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) {
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(chatMessage.getBody());
message.setType(Message.Type.normal);
try {
//if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
//} else {
login();
//}
} catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
Toast.makeText( context,"not sending", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
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() {
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!");
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() {
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);
System.out.println("Body-----"+message.getBody());
if (message.getType() == Message.Type.chat
&& message.getBody() != null) {
final ChatMessage chatMessage = new ChatMessage();
chatMessage.setBody(message.getBody());
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();
}
});
}
}
}
//connect to server
private class MyOpenfireLoginTask extends AsyncTask<String, String, String> {
private Context mContext;
String username, password;
ProgressDialog dialog;
public MyOpenfireLoginTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(mContext);
dialog.setMessage(getResources().getString(R.string.loading_txt));
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
username = params[0];
password = params[1];
Log.e("Login using ", username + " , " + password);
Config.config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword(username, password)
.setHost(Config.openfire_host_server_IP)
.setResource(Config.openfire_host_server_RESOURCE)
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setServiceName(Config.openfire_host_server_SERVICE)
.setPort(Config.openfire_host_server_CHAT_PORT)
.setDebuggerEnabled(true)
.build();
Config.conn1 = new XMPPTCPConnection(Config.config);
Config.conn1.setPacketReplyTimeout(5000);
try {
Config.conn1.connect();
if (Config.conn1.isConnected()) {
Log.w("app", "conn done");
}
Config.conn1.login();
if (Config.conn1.isAuthenticated()) {
Log.w("app", "Auth done");
} else {
Log.e("User Not Authenticated", "Needs to Update Password");
}
} catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (Config.conn1.isAuthenticated()) {
setUserPresence(0);
//store data in session
sharedPreferenceManager.setUsername(username);
sharedPreferenceManager.setUserPsw(password);
if (UserListActivity.mActivity != null) {
UserListActivity.mActivity.finish();
}
Intent intent = new Intent(mContext, HomeActivity.class);
mContext.startActivity(intent);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
if (SignupActivity.mActivity != null) {
SignupActivity.mActivity.finish();
}
finish();
} else {
Log.e(TAG, "username password wrong");
CommonUtils.commonToast(mContext, mContext.getResources().getString(R.string.invalid_uname_psw));
// CommonUtils.commonToast(mContext,mContext.getResources().getString(R.string.loading_txt));
}
}
}
// check connection is available or not !if not redirect to login screen.
public boolean isUserConnectedToServer(Activity mActivity) {
if (Config.conn1 != null && Config.conn1.isConnected()) {
Log.e(TAG, "----->Connected");
setUserPresence(0);
return true;
} else {
Log.e(TAG, "----->Not connected");
setUserPresence(5);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
return false;
}
}
//disconnect user from server
public void logoutUser(Activity mActivity) {
if (Config.conn1 != null && Config.conn1.isConnected()) {
Log.e(TAG, "-----isConnected------Logout");
setUserPresence(5);
Config.conn1.disconnect();
} else {
Log.e(TAG, "-----disconnect-------Not connected");
}
sharedPreferenceManager.clearData();
//stop background service
stopBackgroundService(mActivity);
if (LoginActivity.mActivity != null) {
LoginActivity.mActivity.finish();
}
Intent intent = new Intent(mActivity, LoginActivity.class);
mActivity.startActivity(intent);
mActivity.finish();
}
Related
I am using this code for connecting my android app to XMPP server i.e Openfire Server with Smack API
public class MyXMPP {
private static final String DOMAIN = "localhost";
private static final String HOST = "192.168.1.2";
private static final int PORT = 9090;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
Context c;
//Initialize
public void init(Context context,String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
this.c=context;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
// Disconnect Function
public void disconnectConnection(){
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
//connection.setPacketReplyTimeout(30000);
connection.connect();
login();
connected = true;
} catch (IOException e) {
}
catch (SmackException e)
{
Log.v("errror",e.getMessage());
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
public void sendMsg() {
if (connection.isConnected()== true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat("concurer#nimbuzz.com");
try {
newChat.sendMessage("Howdy!");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(userName, passWord);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
// Toast.makeText(c,"Login successfully",Toast.LENGTH_LONG).show();
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
//Connection Listener to check connection state
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
}
});
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() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!"+arg0);
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() {
}
});
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
}
});
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;
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
}
});
}
}
}
but getting an exception i.e "No response received within reply timeout. A timeout was 10000ms (~10s). Used filter: No filter used or filter was 'null'.".
If am I missing something in my code, please let me know.
I am using this code for connecting my android app to xmpp server i.e openfire Server with Smack api
public class MyXMPP {
private static final String DOMAIN = "nimbuzz.com";
private static final String HOST = "o.nimbuzz.com";
private static final int PORT = 5222;
private String userName ="";
private String passWord = "";
AbstractXMPPConnection connection ;
ChatManager chatmanager ;
Chat newChat;
XMPPConnectionListener connectionListener = new XMPPConnectionListener();
private boolean connected;
private boolean isToasted;
private boolean chat_created;
private boolean loggedin;
//Initialize
public void init(String userId,String pwd ) {
Log.i("XMPP", "Initializing!");
this.userName = userId;
this.passWord = pwd;
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(userName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName("localhost");
configBuilder.setHost("192.168.1.2");
configBuilder.setPort(5222);
//configBuilder.setDebuggerEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
}
// Disconnect Function
public void disconnectConnection(){
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
}
}).start();
}
public void connectConnection()
{
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
} catch (IOException e) {
}
catch (SmackException e)
{
Log.v("errror",e.getMessage());
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
public void sendMsg() {
if (connection.isConnected()== true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat("concurer#nimbuzz.com");
try {
newChat.sendMessage("Howdy!");
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(userName, passWord);
//Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
//Connection Listener to check connection state
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
}
});
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() {
}
});
Log.d("xmpp", "ConnectionClosedOn Error!");
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() {
}
});
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
}
});
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;
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
}
});
}
}
}
but getting an exception i.e "The following addresses failed: '192.168.1.2:9090' failed because java.net.SocketTimeoutException: failed to connect to /192.168.1.2 (port 9090) after 30000ms".If i am missing something in my code please let me know.
I want to imaplement xmpp connection in my application i refered lot of tutorials in google,but i cnnot get clear idea.
please some one help me out this problem,give suggetion how to implemnt xmpp connection.
thank you.
first You Have to add build.gradle
compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-im:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-extensions:4.1.0-rc1"
then create LocalBinder class
public class LocalBinder<S> extends Binder {
private final WeakReference<S> mService;
public LocalBinder(final S service) {
mService = new WeakReference<S>(service);
}
public S getService() {
return mService.get();
}
}
Then Create service class
public class XmppService extends Service {
public static MyXMPP xmpp;
private String ServiceName = "", HostAddress = "";
private String USERNAME = "";
private String PASSWORD = "";
private SessionManager sessionManager;
#Override
public IBinder onBind(final Intent intent) {
return new LocalBinder<XmppService>(this);
}
#Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate() {
sessionManager = new SessionManager(XmppService.this);
ServiceName = Your Service Name ;
HostAddress = Your Host Address;
USERNAME = your xmpp server user name;
PASSWORD = Your xmpp server pwd;
xmpp = MyXMPP.getInstance(XmppService.this, ServiceName, HostAddress, USERNAME, PASSWORD);
xmpp.connect("onCreate");
}
#Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
MyXMPP.instance=null;
MyXMPP.instanceCreated=false;
xmpp.connection.disconnect();
System.out.println("--------------Xmpp Service Stopped-----------");
}
}
create xmpp class
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 boolean server_chat_created = false;
private String serviceName = "", hostAddress = "";
public static XMPPTCPConnection connection;
public static String loginUser;
public static String passwordUser;
XmppService context;
public static MyXMPP instance = null;
public static boolean instanceCreated = false;
private static ChatHandler chatHandler;
public MyXMPP(XmppService context, String mServiceName, String mHostAddress, String loginUser, String passwordUser) {
this.serviceName = mServiceName;
this.hostAddress = mHostAddress;
this.loginUser = loginUser;
this.passwordUser = passwordUser;
this.context = context;
init();
}
public static MyXMPP getInstance(XmppService context, String mServiceName, String mHostAddress, String user, String pass) {
if (instance == null) {
instance = new MyXMPP(context, mServiceName, mHostAddress, user, pass);
instanceCreated = true;
}
return instance;
}
public org.jivesoftware.smack.chat.Chat Mychat ,MyServerchat;
ChatManagerListenerImpl mChatManagerListener;
MMessageListener mMessageListener;
String text = "";
String mMessage = "", mReceiver = "";
static {
try {
Class.forName("org.jivesoftware.smack.ReconnectionManager");
} catch (ClassNotFoundException ex) {
// problem loading reconnection manager
}
}
public void init() {
mMessageListener = new MMessageListener(context);
mChatManagerListener = new ChatManagerListenerImpl();
initialiseConnection();
}
private void initialiseConnection() {
XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
config.setServiceName(serviceName);
config.setHost(hostAddress);
config.setDebuggerEnabled(true);
config.setConnectTimeout(50000);
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 + "=>connecting....",
Toast.LENGTH_LONG).show();*/
}
});
Log.d("Connect() Function", caller + "=>connecting....");
try {
connection.connect();
ReconnectionManager reconnectionManager =
ReconnectionManager.getInstanceFor(connection);
reconnectionManager.setEnabledPerDefault(false);
reconnectionManager.enableAutomaticReconnection();
/*PingManager pingManager =
PingManager.getInstanceFor(connection);
pingManager.setPingInterval(300);*/
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 {
System.out.println("----login------USERNAME------------" + loginUser);
System.out.println("----login------PASSWORD------------" + passwordUser);
connection.login(loginUser, passwordUser);
Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
// connect("");
} catch (Exception e) {
}
}
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 int sendMessage(String senderID, String mMessage) {
if (!chat_created) {
Mychat = ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
Mychat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* 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 Message Exception", "msg Not sent!" + e.getMessage());
}*/
}
public int sendMessageServer(String senderID, String mMessage) {
if (!server_chat_created) {
MyServerchat =
ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
server_chat_created = true;
}
final Message message = new Message();
message.setBody(mMessage);
message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated()) {
MyServerchat.sendMessage(message);
return 1;
} else {
login();
return 0;
}
} catch (SmackException.NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
return 0;
} catch (Exception e) {
Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
return 0;
}
/* 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 Message Exception", "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!");
System.out.println("-------------ConnectionCLosed!----------------");
instance = null;
connected = false;
chat_created = false;
server_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!");
connected = false;
instance = null;
chat_created = false;
server_chat_created = false;
loggedin = false;
}
#Override
public void reconnectingIn(int arg0) {
Log.d("xmpp", "Reconnectingin " + arg0);
System.out.println("----------prem 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;
instance = null;
chat_created = false;
server_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;
server_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;
server_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)
{
System.out.println("-----------xmpp message-------------" + message.getBody());
try
{
if (chatHandler == null) {
chatHandler = new ChatHandler(context);
}
chatHandler.onHandleChatMessage(message);
}
catch (Exception e) {
}
}
}
}
}
Next Handle the Received Data from xmpp Class
public class ChatHandler {
private Context context;
private IntentService service;
private GEODBHelper myDBHelper;
private SessionManager session;
public ChatHandler(Context context, IntentService service) {
this.context = context;
this.service = service;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public ChatHandler(Context context) {
this.context = context;
session = new SessionManager(context);
myDBHelper = new GEODBHelper(context);
}
public void onHandleChatMessage(Message message) {
try {
String data = URLDecoder.decode(message.getBody(), "UTF-8");
JSONObject messageObject = new JSONObject(data);
}
catch (Exception e) {
}
}
add to manifest
<service
android:name="com.app.xmpp.XmppService"
android:enabled="true" />
Start xmpp service
startService(new Intent(myclass.this, XmppService.class));
stop xmpp service
stopService(new Intent(getApplicationContext(), XmppService.class));
You can integrate Quickblox API it has multiple features like User Management, Chat, Group Chat, Video & Audio Calling.
Quickblox
Try this example https://github.com/blikoon/Rooster
It worked for me. I did my own messenger using this source
Goog luck
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();
}
}
My Android app is maintaining a socket connection with the server and this connection works fine when the device is connected to Wi-Fi and fails only when the device is connected to the mobile network. Error trace is as follows
org.java_websocket.exceptions.InvalidFrameException: bad rsv 3
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.drafts.Draft_10.translateSingleFrame(Draft_10.java:308)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.drafts.Draft_10.translateFrame(Draft_10.java:285)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.WebSocketImpl.decodeFrames(WebSocketImpl.java:321)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.WebSocketImpl.decode(WebSocketImpl.java:164)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at org.java_websocket.client.WebSocketClient.run(WebSocketClient.java:185)
03-08 14:56:40.909 20527-21343/com.mydomain.myapp.staging W/System.err: at java.lang.Thread.run(Thread.java:841)
03-08 14:56:40.914 20527-21343/com.mydomain.myapp.staging D/WebSocketService: Socket closed: bad rsv 3
03-08 14:56:40.914 20527-21343/com.mydomain.myapp.staging D/WebSocketService: Socket closed- code: 1002, reason: bad rsv 3
My code is as follows,
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
public class WebSocketService extends Service {
public static final String WEB_SOCKET_SERVICE_RECEIVER = "com.mydomain.myapp.WebSocketServiceReceiver";
public static final String EXTRA_COMMAND = "extraCommand";
public static final String EXTRA_MESSAGE = "extraMessage";
public static final int COMMAND_STOP = -2;
public static final int COMMAND_SEND_MESSAGE = -3;
public static void stopService(Context context, String message) {
Intent intent = new Intent(WEB_SOCKET_SERVICE_RECEIVER);
intent.putExtra(EXTRA_COMMAND, COMMAND_STOP);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("WebSocketService", "onStartCommand");
if (!mStarted) {
mStarted = true;
mWebSocketClosed = false;
mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE))
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"WebSocketServiceWakeLock");
pingPackets = new Stack<PingPacket>();
registerReceiver(mReceiver, new IntentFilter(
WEB_SOCKET_SERVICE_RECEIVER));
try {
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("WebSocketService", "onDestroy");
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacksAndMessages(null);
mFallbackHandler = null;
}
if (mListenForConnectivity) {
mListenForConnectivity = false;
try {
unregisterReceiver(mProviderChangedListener);
} catch (Exception e) {
e.printStackTrace();
}
}
mStarted = false;
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
e.printStackTrace();
}
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
stopWebSocket();
}
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacksAndMessages(null);
mFallbackHandler = null;
}
if (mListenForConnectivity) {
mListenForConnectivity = false;
try {
unregisterReceiver(mProviderChangedListener);
} catch (Exception e) {
e.printStackTrace();
}
}
mStarted = false;
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
e.printStackTrace();
}
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
stopWebSocket();
}
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
protected void startWebSocket() throws URISyntaxException {
Log.d("WebSocketServce", "startWebSocket");
String webSocketBaseURL = BuildSpecificConstants.WEB_SOCKET_BASE_URL;
mWebSocketClient = new WebSocketClient(new URI(webSocketBaseURL
+ "?auth_token="
+ SessionManager.getInstance(getApplicationContext())
.getAPIKey())) {
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.d("WebSocketServce", "onOpen");
if (!mWakeLock.isHeld()) {
mWakeLock.acquire();
Log.d("WebSocketService", "WakeLock acquired");
}
startPingProtocol();
if (mPendingMessage != null) {
sendMessage(mPendingMessage);
}
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE).edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, false);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_CONNECTED);
sendBroadcast(intent);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
.cancel(AppConstants.CONNECTION_ERROR_NOTIFICATION_ID);
}
#Override
public void onWebsocketPong(WebSocket conn, Framedata frame) {
super.onWebsocketPong(conn, frame);
try {
if (frame.getOpcode() == Opcode.PONG) {
if (!pingPackets.isEmpty()) {
PingPacket returnedPing = pingPackets.get(0);
if (returnedPing != null) {
returnedPing.consume();
pingPackets.remove(0);
Log.d("WebSocketService", returnedPing.id
+ " pong received");
failedPingCount = 0;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String message) {
try {
JSONObject eventJson = new JSONObject(message);
Log.d("WebSocketService", "Received: " + message);
String eventType = eventJson
.getString(IncomingMessageParams.EVENT);
if (eventType.equals(EventTypes.NEW_BOOKING)) {
Trip trip = Trip
.decodeJSON(
eventJson
.getJSONObject(BookingsResponseParams.KEY_BOOKING),
eventJson.getJSONObject("passenger"),
eventJson.getJSONArray("locations"),
eventJson.optJSONObject("coupon"),
SessionManager
.getInstance(WebSocketService.this));
Intent intent = new Intent(WebSocketService.this,
IncomingBookingActivity.class);
intent.putExtra(IncomingBookingActivity.EXTRA_BOOKING,
trip);
intent.putExtra(
MainActivity.EXTRA_COUNT_DOWN_TIME,
eventJson
.getInt(IncomingMessageParams.LOOKUP_TIME));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
SessionManager.getInstance(getApplicationContext())
.setStatus(DriverStatus.BUSY);
LocationUpdateService
.sendStatusChange(WebSocketService.this);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onError(Exception ex) {
ex.printStackTrace();
Log.d("WebSocketService", "Socket closed: " + ex.getMessage());
if (!Helper.checkNetworkStatus(WebSocketService.this)) {
mListenForConnectivity = true;
registerReceiver(mProviderChangedListener,
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
} else {
if (!mWebSocketClosed) {
reconnect();
}
}
if (!mWebSocketClosed) {
showErrorNotification();
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE)
.edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, true);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_DISCONNECTED);
sendBroadcast(intent);
}
}
#Override
public void onClose(int code, String reason, boolean remote) {
Log.d("WebSocketService", "Socket closed- code: " + code
+ ", reason: " + reason);
if (code != CloseFrame.NORMAL) {
if (!Helper.checkNetworkStatus(WebSocketService.this)) {
mListenForConnectivity = true;
registerReceiver(
mProviderChangedListener,
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
} else {
reconnect();
}
showErrorNotification();
Editor editor = getSharedPreferences(
SharedPrefKeys.APP_PREFERENCES, MODE_PRIVATE)
.edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, true);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_DISCONNECTED);
sendBroadcast(intent);
}
}
};
if (BuildConfig.FLAVOR.equals("production")) {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
} };
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
SSLSocketFactory factory = sslContext.getSocketFactory();
try {
mWebSocketClient.setSocket(factory.createSocket());
} catch (IOException e) {
e.printStackTrace();
}
}
mWebSocketClient.connect();
}
protected void startPingProtocol() {
pingCounter = 0;
failedPingCount = 0;
pingRunning = true;
if (pingThread == null || !pingThread.isAlive()) {
pingThread = new Thread(new Runnable() {
#Override
public void run() {
while (pingRunning) {
if (failedPingCount < 3) {
PingPacket packet = new PingPacket(pingCounter);
Log.d("WebSocketService", "sending ping "
+ pingCounter);
pingPackets.add(packet);
packet.sendPing(mWebSocketClient);
pingCounter++;
pingCounter %= Byte.MAX_VALUE;
} else {
stopPingProtocol();
Log.d("WebSocketService", "connection lost");
}
try {
Thread.sleep(AppConstants.PING_SPAWN_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
private void stopPingProtocol() {
if (pingThread != null && pingThread.isAlive()) {
pingRunning = false;
pingThread.interrupt();
for (int i = 0; i < pingPackets.size(); i++) {
pingPackets.get(i).consume();
}
pingPackets.clear();
}
}
protected void reconnect() {
if (mConnectionAttempt < AppConstants.MAX_WEB_SOCKET_RECONNECTS) {
mFallbackHandler = new Handler(Looper.getMainLooper());
mFallbackHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (mFallbackHandler != null) {
mFallbackHandler.removeCallbacks(this);
mFallbackHandler = null;
}
try {
stopWebSocket();
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
mConnectionAttempt++;
}
}, AppConstants.WEB_SOCKET_BASE_FALLBACK_TIME * mConnectionAttempt);
} else {
if (mWakeLock.isHeld()) {
mWakeLock.release();
Log.d("WebSocketService", "WakeLock released");
}
}
}
protected void sendMessage(String message) {
if (mWebSocketClient != null && mWebSocketClient.isOpen()) {
mWebSocketClient.send(message);
mConnectionAttempt = 1;
Log.d("WebSocketService", "Send: " + message);
} else {
mPendingMessage = message;
}
}
protected void stopWebSocket() {
Log.d("WebSocketService", "Closing");
mWebSocketClosed = true;
mWebSocketClient.close();
stopPingProtocol();
Editor editor = getSharedPreferences(SharedPrefKeys.APP_PREFERENCES,
MODE_PRIVATE).edit();
editor.putBoolean(SharedPrefKeys.WEB_SOCKET_ERROR, false);
editor.commit();
Intent intent = new Intent(
BaseActivity.BROADCAST_RECEIVER_INTENT_FILTER);
intent.putExtra(BaseActivity.BROADCAST_EXTRA_TYPE,
BaseActivity.BROADCAST_TYPE_WEB_SOCKET_CONNECTED);
sendBroadcast(intent);
}
private WakefulBroadcastReceiver mProviderChangedListener = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (Helper.checkNetworkStatus(context)) {
mListenForConnectivity = false;
try {
unregisterReceiver(this);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
startWebSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
};
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int command = intent.getIntExtra(EXTRA_COMMAND, -1);
switch (command) {
case COMMAND_STOP:
sendMessage(intent.getStringExtra(EXTRA_MESSAGE));
stopSelf();
break;
case COMMAND_SEND_MESSAGE:
sendMessage(intent.getStringExtra(EXTRA_MESSAGE));
break;
default:
break;
}
}
};
Private class,
private class PingPacket { protected byte id;
protected Timer timer;
protected PingPacket(byte id) {
this.id = id;
timer = new Timer();
}
protected void sendPing(WebSocketClient client) {
FramedataImpl1 frame = new FramedataImpl1(Opcode.PING);
frame.setFin(true);
client.sendFrame(frame);
Log.d("WebSocketService", id + " ping sent");
timer.schedule(new TimerTask() {
#Override
public void run() {
failedPingCount++;
Log.d("WebSocketService", "Ping " + id + " failed");
}
}, AppConstants.PING_EXPIRE_DELAY);
}
protected void consume() {
timer.cancel();
timer.purge();
}
}
}
What could possibly be causing this?
The InvalidFrameException with a message "bad rsv 3" implies that the protocol exchanged in the WebSocket connection is wrong. Your stack trace implies that Draft_10 is used, but it is too old.
FYI: You can find other WebSocket client libraries for Android in "Which WebSocket library to use in Android app?".