OpenFire Instant Messaging Service build and smack access

Source: Internet
Author: User
Tags ssl certificate server port

OpenFire is an open-source, real-time collaboration server developed in the Java programming language based on extensible Communication and Presentation Protocol (XMPP). OpenFire is easy to install and use, and is managed with the Web. A single server can support tens of thousands of concurrent users.

First, go to the OpenFire official web site to download the OpenFire server package with the Smack client call package.

http://www.igniterealtime.org/projects/index.jsp

After opening here can see openfire,spark,smack these three things, I briefly explain what they are, OpenFire is running on the server, spark and smack are running on the client, and Spark is a built application, Download the installation can be used (see below), smack is to provide access to the OpenFire call interface, is to do development write code.



OpenFire after the download, if it is a win version, then it is an EXE installation package, run the next step, you will need to configure the database (OpenFire of course, need to support the database, such as to save the account and so on information). Specifically, you can refer to this http://jingyan.baidu.com/article/2c8c281df16ad30008252ae4.html


OpenFire after successful installation, download The smack package containing the corresponding interface jar package, import into our project (different versions of the Smack jar may not be the same)



Write our program to access Operfire

Import Java.util.collection;import Java.util.iterator;import Javax.net.socketfactory;import Org.jivesoftware.smack.accountmanager;import Org.jivesoftware.smack.chat;import Org.jivesoftware.smack.chatmanager;import Org.jivesoftware.smack.chatmanagerlistener;import Org.jivesoftware.smack.connection;import Org.jivesoftware.smack.connectionconfiguration;import Org.jivesoftware.smack.messagelistener;import Org.jivesoftware.smack.roster;import Org.jivesoftware.smack.rosterentry;import Org.jivesoftware.smack.xmppconnection;import Org.jivesoftware.smack.xmppexception;import Org.jivesoftware.smack.packet.message;import Org.jivesoftware.smack.packet.presence;import Org.jivesoftware.smack.packet.session;import    Org.jivesoftware.smack.packet.message.type;public class Smackutil {private Connection Connection;    Private Connectionconfiguration config;        /** OpenFire Server address */private final static String server = "10.100.53.65"; Private final void print (Object o) {if (O! =NULL) {System.out.println (o);  }} private final void print (Object O, Object ... args) {if (o! = null && args! = null &&            Args.length > 0) {String s = o.tostring (); for (int i = 0; i < args.length; i++) {String item = args[i] = = null?                "": args[i].tostring ();                if (S.contains ("{" + i + "}")) {s = S.replace ("{" + i + "}", item);                } else {s + = "" + Item;        }} System.out.println (s); }}/** * Initial smack the basic configuration of the OpenFire server link */public void init () {try {//connection = n            EW xmppconnection (server);            Connection.connect (); /** 5222 is the OpenFire server default communication port, you can log in http://10.100.53.65:9090/to the Administrator console to view the client-to-server port */config = new Connectionconfigur                        ation (server, 5222); /** whether compression is enabled */Config.setcompressionenAbled (TRUE);            /** Whether security authentication is enabled */config.setsaslauthenticationenabled (TRUE);            /** whether debugging is enabled */config.setdebuggerenabled (FALSE);            Config.setreconnectionallowed (TRUE);                        Config.setrosterloadedatlogin (TRUE);            /** Create Connection link */connection = new xmppconnection (config);            /** Establish connection */Connection.connect ();        SYSTEM.OUT.PRINTLN ("Connection success");        } catch (Xmppexception e) {e.printstacktrace ();        } print (connection);    Print (Connection.getconnectionid ());            } public void Destory () {if (connection! = null) {connection.disconnect ();        connection = null;  }}/** * connectionconfiguration basic Configuration related information */public void Seeconfig () {print ("Pkcs11library:        "+ config.getpkcs11library ());        Print ("ServiceName: {0}", Config.getservicename ()); SSL Certificate Password print ("Truststorepassword: {0} ", Config.gettruststorepassword ());        Print ("Truststorepath: {0}", Config.gettruststorepath ());                Print ("Truststoretype: {0}", Config.gettruststoretype ());        Socketfactory socketfactory = Config.getsocketfactory ();    Print ("Socketfactory: {0}", socketfactory); }/** * Connection Basic method information */public void seeconnection () {/** user management */Accountmanager Acco        Untmanager = Connection.getaccountmanager ();        For (String attr:accountManager.getAccountAttributes ()) {print ("Accountattribute: {0}", attr);        } print ("Accountinstructions: {0}", Accountmanager.getaccountinstructions ());        /** whether the link is */print ("isconnected:", connection.isconnected ());        Print ("isanonymous:", connection.isanonymous ());        Whether the/** has permission */print ("IsAuthenticated:", connection.isauthenticated ());        Print ("IsSecureConnection:", connection.issecureconnection ());     /** whether to use compression */   Print ("Isusingcompression:", connection.isusingcompression ()); }/** * Create user * @param username * @param password * * public void CreateUser (String username, stri    ng password) {Accountmanager Accountmanager = Connection.getaccountmanager (); Try {/** creates a user; You can view information about the user/group in the Administrator console page http://10.100.53.65:9090/user-summary.jsp to see if the user was created successfully//Accountmanager.cre    Ateaccount (username, password);    /** Change Password */Accountmanager.changepassword ("abc");    } catch (Xmppexception e) {e.printstacktrace (); }}/** * Change Password * @param username * @param password * * public void ChangePassword (String p    Assword) {Accountmanager Accountmanager = Connection.getaccountmanager ();    try {/** Change Password */Accountmanager.changepassword ("123456");    } catch (Xmppexception e) {e.printstacktrace (); }}/** * User login * @param username * @param password * * public void Login (String Userna Me, StringPassword) {try {/** user login, username, password */connection.login (username, password);        } catch (Xmppexception e) {e.printstacktrace ();                }/** Gets the current login user */print ("User:", Connection.getuser ());               /** all user groups */roster roster = Connection.getroster (); /* Try {roster.createentry ("test55", "test55", null);//Add friends, do not add as friends can also send and receive messages} catch (Xmppexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();} *//** Friends User group, you can use spark to add user friends, so that you can query the relevant data */collection<rosterentry> Rosterentiry = roster.        GetEntries ();        Iterator<rosterentry> iter = Rosterentiry.iterator ();            while (Iter.hasnext ()) {Rosterentry entry = Iter.next (); Print ("Groups: {0}, Name: {1}, Status: {2}, Type: {3}, User: {4}", Entry.getgroups (), Entry.getname (), Entry.getstatus (),        Entry.gettype (), entry);   } print ("-------------------------------");     /** not processed, verified friends, added friends, did not get the other side of the agreement * * collection<rosterentry> unfiledentries = roster.getunfiledentries ();        iter = Unfiledentries.iterator ();            while (Iter.hasnext ()) {Rosterentry entry = Iter.next (); Print ("Groups: {0}, Name: {1}, Status: {2}, Type: {3}, User: {4}", Entry.getgroups (), Entry.getname (), Entry.getstatus (),        Entry.gettype (), entry); }}/** * Add message Listener */public void Addmsglistener () {//Listen to received messages Connection.getchatmanager (). Addchatlistener (New Chatmanagerlistener () {//can listen to messages sent by all users @Override public void chatcreated (chat chat, Boolean createdlocally) {Chat.addmessagelistener (new MessageListener () {public void ProcessMessage (chat chat, Message me      Ssage) {//string from = Message.getfrom ();      String BODY = Message.getbody ();        System.out.println ("Body:" +message.getbody ());      }      });        }    });     }/** * Packet message chat * @param from* @param to * @param msg */public void sendpacketmsg (string from, string to, String msg) {//try {//                Connection.login (from, from),//} catch (Xmppexception e) {//E.printstacktrace ();/}  /** change user state, available=true means online, false means offline, status state signature; When you log in, you can see the status of your login in the Spark client software */presence Presence        = new Presence (Presence.Type.available);        Presence.setstatus ("Q Me");                Connection.sendpacket (presence);        Session Session = new session ();        String sessid = Session.nextid ();        Connection.sendpacket (session);        Message message = new Message (to+ "@" + server, type.chat);        Message message = new Message (sessid, type.chat);        Message.setbody (msg);    Connection.sendpacket (message); }/** * Chat message chats * @param from * @param to * @param msg */public void sendchatmsg (String fr      OM, string to, String msg) {/** set state *///try {//      Connection.login (from, from),//} catch (Xmppexception e) {//E.printstacktrace ();/}        /** Set Status */presence presence = new presence (Presence.Type.available);        Presence.setstatus ("Q Me");                Connection.sendpacket (presence);        /** gets the chat manager for the currently logged-on user */Chatmanager Chatmanager = Connection.getchatmanager (); /** Create a chat for the specified user to listen to the message sent by the other person */chat chat = chatmanager.createchat (to+ "@" + server, new MessageListener () {//Only listen for the The message @overridepublic void ProcessMessage (chat chat, message message) {SYSTEM.OUT.PRINTLN ("Body:" +message.getbody ())        ;}});                        try {/** Send message */Chat.sendmessage (msg);            /** sends a message with the messages object *///msg = new Message ();//Message.setbody ("message");//        Message.setproperty ("Color", "red");//chat.sendmessage (message);       } catch (Xmppexception e) {e.printstacktrace (); }    }    } 

Create a test account for two communications

public static void Main (string[] args) {Smackutil smackutil = new Smackutil (); Smackutil.init (); Smackutil.seeconfig (); Smackutil.seeconnection (); Smackutil.createuser ("Test1", "test1");}

public static void Main (string[] args) {Smackutil smackutil = new Smackutil (); Smackutil.init (); Smackutil.seeconfig (); Smackutil.seeconnection (); Smackutil.createuser ("Test2", "test2");}

Log in and send a message using the account you just created

Test1 log in and send a message:

public static void Main (string[] args) {Smackutil smackutil = new Smackutil (); Smackutil.init (); Smackutil.seeconfig (); Smackutil.seeconnection (); Smackutil.login ("Test1", "test1"); Smackutil.addmsglistener (); Smackutil.sendchatmsg (" Test1 "," Test2 "," 1111111111111111111111111111111111111 ") smackutil.sendpacketmsg (" Test1 "," Test2 "," 1111111111111111111111111111111111111 "); try {thread.sleep (1000*1000);} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}}

test2 Log in and send a message:

public static void Main (string[] args) {Smackutil smackutil = new Smackutil (); Smackutil.init (); Smackutil.seeconfig (); Smackutil.seeconnection (); Smackutil.login ("Test2", "test2"); Smackutil.addmsglistener (); Smackutil.sendchatmsg (" Test2 "," Test1 "," 222222222222222222222222222222222222222 ") smackutil.sendpacketmsg (" Test2 "," Test1 "," 222222222222222222222222222222222222222 "); try {thread.sleep (100*1000);} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}}

You can see the received message on both consoles after running



See here, the explanation has been able to communicate properly, send and receive messages.


OpenFire Instant Messaging Service build and smack access

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.