Create a chat application using openfire server and smack library

Targeted audience for this blog is developers having knowledge of core java, android, XMPP Protocol, socket programming and FTP protocol.

Following are the steps to build the chat application using openfire server and smack library :

1.) Install openfire server and configure on pc :-

  • You can follow :

  The typical openfire server admin console looks like below :




  •  You can download and install lots of available plugins and extend the functionality of the server.
     Below is the source from where you can get the openfire plugins.
2.) Add the smack library into your android project, below are the source for integrating the latest smack library for android :

  •  Smack is very good library for developing chat applications.
  • Add the required libraries in application level build.gradle.

Example:



dependencies {

implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'

implementation group: 'org.jxmpp', name: 'jxmpp-jid', version: '0.5.0' 

// Optional for XMPP TCP Connection 
implementation 'org.igniterealtime.smack:smack-android-extensions:4.1.0'
implementation 'org.igniterealtime.smack:smack-tcp:4.1.0'  
}

       
 


3.) Now you can start coding and connect to openfire server using smack library's functions:

    a.) To connect to openfire server:   



//XMPP configuration instance
public static XMPPTCPConnectionConfiguration config;


//XMPP connection instance
public static AbstractXMPPConnection conn1;

//IP address of Openfire chat server
public static final String openfire_host_server_IP = "xx.x.x.x.x.x.x."; //(Example : 127.0.0.1)

//(The key is required in case you use REST API of Openfire)
public static final String openfire_host_server_key = "--------------------";


//Port number of the chat server
public static final int openfire_host_server_PORT = 5222;


//(Resource name of the server)
public static final String openfire_host_server_RESOURCE = "------------";



//XMPP Configuration to connect Openfire server

//This is service name in case you use multi user chat
public static final String openfire_host_server_CONFERENCE_SERVICE = "conference.//////";

        

public static final String openfire_host_server_SERVICE = "//////";
        config = XMPPTCPConnectionConfiguration.builder()
        .setPort(Config.openfire_host_server_CHAT_PORT)
        .setUsernameAndPassword(loginname, password)
        .setHost(Config.openfire_host_server_IP)
        .setResource(Config.openfire_host_server_RESOURCE)
        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
        .setServiceName(Config.openfire_host_server_SERVICE)

        conn1.setPacketReplyTimeout(5000); // If not connected within 5 seconds then conn1 will be disconnected
        .setDebuggerEnabled(true) // to view what's happening in detail
        .build();


//Attempt to connect to Openfire server

        if (conn1.isConnected()) {

        conn1 = new XMPPTCPConnection(Config.config);
        try {
        conn1.connect();
        Log.w("app", "conn done");
        }
        conn1.login();
        if (conn1.isAuthenticated()) {
        Log.w("app", "Auth done");
        Log.e("User Not Authenticated", "Needs to Update Password");
        } else {} catch (Exception e) {}
        Log.w("app", e.toString());
       
 


4.) After connecting successfully you can either do single chat or group chat, below is the code to send message to single user :
   
   a.) SINGLE CHAT



 public static ChatManager chatManager;

if (chatManager == null) {

 chatManager = ChatManager.getInstanceFor(conn1);
}
if (chatManager != null) {

 @Override public void chatCreated(Chat chat, boolean createdLocally) {
  chatManager.addChatListener(new ChatManagerListener() {

    @Override public void processMessage(final Chat chat, final Message message) {
     chat.addMessageListener(new ChatMessageListener() {

       Log.e("Message Received : ", message.getBody());
       System.out.println("Received message: " + (message != null ? message.getBody() : "NULL"));

       Log.e("Else Part ", "Connection Null");
       Log.e("Message ID : ", message.getStanzaId());


      }
     });

   } else {
    Log.w("app", chat.toString());


   }

  });



}
       
 

Below source shows the format of XMPP Message :

b.) MULTIUSERCHAT (GROUP CHAT) :  

Below is code for implementing multiuserchat, for this first you need to add/install MUC plugin in  openfire server.
After that you code as below:



 // Chat group name
public String myMUCfullName = groupName.toLowerCase() + "@" + openfire_host_server_CONFERENCE_SERVICE;


// Group chat manager instance

// Group chat instance
public MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(conn1);

/*Message instance that need to send in group
public MultiUserChat mMultiUserChat = manager.getMultiUserChat(myMUCfullName);
 
 
which has text and attributes like a profile picture

and chat timestamp*/

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Message msg = new Message();
msg.setBody(filteredMessage);


// Calender instance

Calendar c = Calendar.getInstance();

// Format of chat timestamp

extchatTime.setValue("chatTime", chatTime + "");
String chatTime = df.format(c.getTime());

DefaultExtensionElement extchatTime = new DefaultExtensionElement("chatTime", "urn:xmpp:extchatTime");


// Profile picture extension

extuserProfilePicture.setValue("userProfilePicture", sharedPreferenceManager.getKEY_PROFILEPICTURE() + "");
DefaultExtensionElement extuserProfilePicture = new DefaultExtensionElement("userProfilePicture", "urn:xmpp:extuserProfilePicture");


msg.addExtension(extuserProfilePicture);
msg.addExtension(extchatTime);

/*sending message in group*/

mMultiUserChat.sendMessage(msg);

You can send invites to group by below code:

 for (int member = 0; member < groupmembers.size(); member++) {
  try {

   mMultiUserChat.invite(groupmembers.get(member).getUserName() + "@" + openfire_host_server_CONFERENCE_SERVICE + "/" + openfire_host_server_RESOURCE, "Join the room!!!");
  } catch (SmackException.NotConnectedException e) {
   e.printStackTrace();
  }
 }
       
 



5.) JOIN GROUP :



 mMultiUserChat.join(sharedPreferenceManager.getKEY_LOGINNAME(),null,history,SmackConfiguration.getDefaultPacketReplyTimeout());
       
 

6.) LISTEN TO INVITATIONS :



manager.addInvitationListener(new InvitationListener() {
 @Override public void invitationReceived(XMPPConnection conn, MultiUserChat room, String inviter, String reason, String password, Message message) {
  Toast.makeText(GroupChatActivity.this, "Invitation Received!!", Toast.LENGTH_SHORT).show();
  Log.e("Invite called", "'----");
  Log.e("User", "join room successfully");
  try {
   mMultiUserChat.join(sharedPreferenceManager.getKEY_LOGINNAME()); /*AUTO JOIN*/
  } catch (XMPPException e) {
   e.printStackTrace();
   e.printStackTrace();
   Log.e("User", "join room failed!");
  } catch (SmackException.NotConnectedException e) {

  } catch (SmackException.NoResponseException e) {
   e.printStackTrace();
  }

 }
});
       
 

7.) GET INCOMING MESSAGES :



mMultiUserChat.addMessageListener(new MessageListener() {
 @Override public void processMessage(Message message) {
  if (message.getBody() != null) {
   
   if (message.getBody().length() > 0) {

//Use the message body as per your need, you can display the message into a bubble in the chat list.
   }
  }

 }
}):
       
 


NOTE :


  •  You can also administrate the openfire server using REST API plugin of openfire server.
  •  You can add/update/delete groups/users by GET/POST API of openfire server.

Comments

Most viewed