使用openfire服务器和smack库创建聊天应用程序

此博客的目标受众是具有核心Java,Android,XMPP协议,套接字编程和FTP协议知识的开发人员。

以下是使用openfire服务器和smack库构建聊天应用程序的步骤:

1.) 安装Openfire服务器并在PC上配置 :-

  • 您可以遵循:

 典型的openfire服务器管理控制台如下所示:




  •  您可以下载并安装许多可用的插件,并扩展服务器的功能。
     以下是您可以从中获取openfire插件的来源。
2.) 将smack库添加到您的android项目中,以下是用于集成最新的smack库的源代码 :

  •  Smack是用于开发聊天应用程序的很好的库。
  • 在应用程序级别添加所需的库 build.gradle.

:



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.) 现在,您可以使用smack库的功能开始编码并连接到openfire服务器:

   a。)要连接到openfire服务器:   



//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.) 连接成功后,您可以进行单人聊天或群聊,以下是向单个用户发送消息的代码 :
   
   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());


   }

  });



}
       
 

下面的源代码显示了XMPP消息的格式:

b。)  多用户聊天(群组聊天):  

下面是用于实现多用户聊天的代码,首先,您需要在以下位置添加/安装MUC插件  openfire server.
之后,您将代码编写如下:



 // 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.)加入组:



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

6.)听邀请:



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.)入帐 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.
   }
  }

 }
}):
       
 


注意 :


  •  您还可以使用openfire服务器的REST API插件管理openfire服务器。
  •  您可以通过openfire服务器的GET / POST API添加/更新/删除组/用户。



演示应用程序链接:  //github.com/Darshit2790/ChatAPP

评论

最受关注