Build and test of Android im based openfire+smack chat server

Source: Internet
Author: User

The XMPP protocol (extensible Messaging and PRESENCEPROTOCOL, Extensible Message Processing field protocol) is an XML-based protocol that is designed to address the standards of timely communication and is first implemented in Jabber. It inherits the flexibility of development in the XML environment. As a result, XMPP-based applications have super-scalable capability. and XML is easy to pass through firewalls, so applications built with XMPP are not susceptible to firewalls. Using XMPP as a universal transmission mechanism, different applications in different organizations can communicate effectively.

Get to know a few concepts first

    • OpenFire is primarily a server that manages communication connections to clients and provides some communication and connection information for clients.

    • Smack is mainly the implementation of the XMPP protocol, providing a good set of APIs, so the following operation XMPP is done by using the Smack API, From 4.1.0 onwards, it supports Android, so we use smack directly, of course, this is not supported before the use of Asmack this package, the method is similar to the smack package.

    • Spark is an IM client implementation, which is actually implemented using the Smack API.

Above three in the first and third of the see Http://www.igniterealtime.org/downloads/index.jsp#openfire, we need to download them down, here we download Windows edition

The second is a set of APIs based on XMPP implementations, which we can refer directly to, and in Android Studio we add dependencies directly to Gradle.

    ‘org.igniterealtime.smack:smack-android-extensions:4.1.4‘    ‘org.igniterealtime.smack:smack-tcp:4.1.4‘

Then we need to add network permissions

    <uses-permission android:name="android.permission.INTERNET" />

Next we don't care about the Android side, we first install two software. Install OpenFire first.

Click Install package to open for initialization

Select a language, choose Chinese here

OK, then click Next.

Consent Permission Click Next

Select the installation directory Click Next, here is the default directory

Continue to the next

Wait patiently for the file to be unpacked

Run OpenFire when you click Done

After running successfully Click Launch Admin to complete the remaining installation work in the background

Select language


Server configuration, we change the domain to native LAN IP address

We need to get the IP address of our computer.

The IP address obtained is 10.0.0.24 and the domain is modified to this value

Database we chose to use an external database, so tick the first one

Next is some value, the first item drop-down select MySQL, then the value will be populated. Next we need to add a database to MySQL.

This assumes you have a local MySQL server, open the background, add a user, tick create a database with the same name as the user name and grant all permissions

Change database name and hostname to the corresponding value, username and password for the user and password you just created in MySQL

Select initial Settings

Set OpenFire Admin account password, here account is set to admin, password set yourself

Click Sign in to the admin console

Enter into the background, input the account password to login

After the landing, it's backstage.

Then install Spark and click on the downloaded installation package

Select the installation directory

Click Next

Continue to click Next

Wait for installation to complete

Click Finish to run Spark

Use our Admin Account admin to log in, the server is local, 127.0.0.1

If the login is successful, the following interface will appear

Then we add two test account, in OpenFire backstage, enter this information to add user

Added two test accounts, tests and test1, respectively

The next most important thing is the Android side, before we need to let our phones and computers out of the same LAN, if you are using a simulator, then, there is no problem.

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

Get a connection

Private Xmpptcpconnection getconnection () {String server="10.0.0.24";int port=5222;Xmpptcpconnectionconfiguration. BuilderBuilder = 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 variables

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, log in, log out, send the message logic

@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 (),"Account or password cannot be empty", 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 chatcreat Ed (chat chat, Boolean createdlocally) {chat. Addmessagelistener(New Chatmessagelistener () {@Override publi c 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. MessageMessage1= Android. OS. Message. Obtain();Message1. What=1;Message1. obj="received the 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 = to. GetText(). toString();Final String C = Content. GetText(). toString();if (textutils. IsEmpty(t) | | Textutils. IsEmpty(c)) {Toast. Maketext(Getapplicationcontext (),"Receiving party 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. Notconnectedexceptione) {E. Printstacktrace();} Break;}    }

After receiving the message, you need to do it in the main thread, simply toast.

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

If you use a test account to log in, you will find that you can not login, will report a mistake

The workaround is also relatively simple, go to the OpenFire installation directory and look for the Conf/openfire.xml file

Add code before the last node is closed

  <sasl>    <mechs></mechs>  </sasl>

Restart OpenFire, this time you will find a successful landing, and can normally set the user's online status

Use our Spark test account test1 to log in, the Android side uses test to log in, test the message can be sent successfully.

Very simple we have to go through the whole process, the back if there is a chance to continue to study this thing, in fact, its function is very powerful.

Finally paste the Android source code.

http://download.csdn.net/detail/sbsujjbcy/9139479

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Build and test of Android im based openfire+smack chat server

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.