Android IM-based Openfire + Smack Chat Server construction and testing

Source: Internet
Author: User

Android IM-based Openfire + Smack Chat Server construction and testing

The XMPP protocol (Extensible Messaging and PresenceProtocol) is an XML-based protocol designed to address timely communication standards, it was first implemented on Jabber. It inherits the flexible development in the XML environment. Therefore, XMPP-based applications are highly scalable. XML is easy to pass through the firewall, so applications built with XMPP are not blocked by the firewall. Using XMPP as a general transmission mechanism, different applications in different organizations can communicate effectively.

First, let's take a look at several concepts.

Openfire is mainly used as a server to manage client communication connections and provide client communication information and connection information.

Smack is mainly implemented by the xmpp protocol and provides a set of good APIs. Therefore, the following operations on xmpp are implemented by using the Smack api. Since 4.1.0, Smack supports Android, therefore, we can use Smack directly. Of course, we use the Asmack package before it is not supported. The method is similar to the smack package.

Spark is the implementation of the IM client, but it is actually implemented using the Smack api.

 

The second is a set of XMPP-Based APIS, which can be directly referenced. In Android Studio, we can add dependencies directly in gradle.

    compile 'org.igniterealtime.smack:smack-android-extensions:4.1.4'    compile 'org.igniterealtime.smack:smack-tcp:4.1.4'

Then we need to add network Permissions

    
  

Next, regardless of the android client, we will install two software first. First install openfire.

Click the installation package to open and initialize

Select a language. Here, select Chinese.

Click Next after confirming

Agree to the license and click Next

Select the installation directory and click Next. The default directory is displayed.

Continue to the next step

Wait patiently for the file to be decompressed

Click Finish to run Openfire

After running successfully, click Launch Admin to enter the background to complete the remaining installation.

Select language


Server configuration, we change the domain to the local area network IP address

We need to obtain the IP address of our computer.

The obtained IP address is 10.0.0.24. Change the domain to this value.

Select external database, so select the first database.

Then there are some values. select mysql from the drop-down list of the first item, and the values will be filled. Next we need to add a database in mysql.

Assume that you have a local mysql server, open the background, add a user, select create database with the same name as the user name, and grant all Permissions

Change the database name and hostname to the corresponding value. The user name and password are the user and password you just created in mysql.

Select initial settings

Set the openfire Administrator account password. Here, the account is set to admin and the password is set by yourself.

Click to log on to the console

Log on to the background and enter the account and password to log on.

The background is displayed after successful login.

Then install Spark and click the downloaded installation package

Select the installation directory

Click Next

Click Next

Wait until installation is complete

Click finish to run spark

Use admin as our administrator account to log in. The server is local and 127.0.0.1

If the login succeeds, the following interface will appear:

Then we add two test accounts. In the openfire background, enter the information to add users.

Two test accounts are added: test and test1.

Next, the most important thing is the Android terminal. Before that, we need to make our mobile phone and computer out of the same LAN. If you are using a simulator, then, this problem does not exist.

The obtained IP address is 10.0.0.24, and the next step is to write the code to log on.

Get a connection

 private XMPPTCPConnection getConnection(){        String server=10.0.0.24;        int port=5222;        XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();        builder.setServiceName(server);        builder.setHost(server);        builder.setPort(port);        builder.setCompressionEnabled(false);        builder.setDebuggerEnabled(true);        builder.setSendPresence(true);        builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);        XMPPTCPConnection connection = new XMPPTCPConnection(builder.build());        return connection;    }

Initialize variable

private EditText account, password,to,content;private Button login,logout,send;private  XMPPTCPConnection connection;connection=getConnection();account = (EditText) findViewById(R.id.account);password = (EditText) findViewById(R.id.password);to = (EditText) findViewById(R.id.to);content = (EditText) findViewById(R.id.content);login = (Button) findViewById(R.id.login);logout = (Button) findViewById(R.id.logout);send = (Button) findViewById(R.id.send);login.setOnClickListener(this);logout.setOnClickListener(this);send.setOnClickListener(this);

The implementation of the corresponding click event, that is, the logic for logging in, logging out, and sending messages

@ Override public void onClick (View view) {switch (view. getId () {case R. id. login: {final String a = account. getText (). toString (); final String p = password. getText (). toString (); if (TextUtils. isEmpty (a) | TextUtils. isEmpty (p) {Toast. makeText (getApplicationContext (), the account or password cannot be blank, Toast. LENGTH_LONG ). show (); return;} new Thread (new Runnable () {@ Override public void run () {try {connection. connect (); Connection. login (a, p); Presence presence = new Presence (Presence. type. available); presence. setStatus (I am online); connection. sendStanza (presence); ChatManager chatmanager = ChatManager. getInstanceFor (connection); chatmanager. addChatListener (new ChatManagerListener () {@ Override public void chatCreated (Chat chat, boolean createdLocally) {chat. addMessageListener (new ChatMessageListener () {@ Overri De public void processMessage (Chat chat, Message message) {String content = message. getBody (); if (content! = Null) {Log. e (TAG, from: + message. getFrom () + to: + message. getTo () + message: + message. getBody (); android. OS. message message1 = android. OS. message. obtain (); message1.what = 1; message1.obj = received message: + message. getBody () + from: + message. getFrom (); mHandler. sendMessage (message1) ;}}}) ;}});} catch (SmackException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} catch (XMPPException e) {e. printStackTrace ();}}}). start (); break;} case R. id. logout: connection. disconnect (); break; case R. id. send: final String t =. getText (). toString (); final String c = content. getText (). toString (); if (TextUtils. isEmpty (t) | TextUtils. isEmpty (c) {Toast. makeText (getApplicationContext (), receiver or content, Toast. LENGTH_LONG ). show (); return;} try {ChatManager chatmanager = ChatManager. getInstanceFor (connection); Chat mChat = chatmanager. createChat (t + @ 10.0.0.24); mChat. sendMessage (c);} catch (SmackException. notConnectedException e) {e. printStackTrace ();} break ;}}

After receiving the message, you need to operate it in the main thread, just Toast it

private Handler mHandler=new Handler(){    @Override    public void handleMessage(android.os.Message msg) {        switch (msg.what){            case 1:                Toast.makeText(getApplicationContext(),msg.obj+,Toast.LENGTH_SHORT).show();                break;        }        super.handleMessage(msg);    }};

At this time, if you log on with the test account, you will find that you cannot log on and an error will be reported.

The solution is also relatively simple. Go to the Openfire installation directory and find the conf/openfire. xml file.

Add code before closing the last Node

  
      
   
     PLAIN 
     
  

Restart OpenFire. At this time, you will find that you have successfully logged on and can set the user's online status properly.

Log on to Spark with the test account test1, and log on to Android with the test account to test whether the message can be sent successfully.

Source code.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.