Development environment: Android Studio Front-end language: Java(based on the open source Smack library) Server language: Java(based on the open source OpenFire)Copy the code

Step 1: Prepare a server, or run it locally

Step 2: Install the pagoda panelwww.bt.cn/

Step 3: Install Tomcat in the app store

Step 4: Install OpenFirewww.igniterealtime.org/projects/op…

Installation steps are omitted, but baidu

Step 5: Add dependency Smack to android projects

/ / instant messaging client smack implementation 'org. Igniterealtime. Smack, smack - android - extensions: 4.4.4' implementation 'org. Igniterealtime. Smack, smack - TCP: 4.4.4'Copy the code

Step 6: Write the configuration and connect to the login server code

XMPPTCPConnectionConfiguration config; Try {config = XMPPTCPConnectionConfiguration. Builder (). SetXmppDomain (" XXXXX ") / / set the host name, namely the hostName. SetHostAddress ( Inetaddress.getbyname (" XXXXX ")) // setHost IP address or domain name.sethost (" XXXXX ") // same as above.setport (5222) // set port.setconnecttimeout ( 600000) / / sets the connection timeout time. SetSecurityMode (ConnectionConfiguration. SecurityMode. Disabled) / / set whether to enable a secure connection .setCompressionEnabled(true) // Enable compression, Can save traffic. SetSendPresence (false) / / delivery status notification. AllowEmptyOrNullUsernames () / / allow the user name is empty or NULL. The build (); XMPPTCPConnection connection = new XMPPTCPConnection( config ); / / according to the configuration to generate a link connection setUseStreamManagement (true); / / open flow management connection. SetUseStreamManagementResumption (true); connection.connect(); } catch(Exception e) {e.printStackTrace(); Attributes = new HashMap<String, String> attributes = new HashMap<>(); // Additional information attributes. Put ("name", "account name"); AccountManager.sensitiveOperationOverInsecureConnectionDefault( true ); / / whether to allow sensitive operations (based on) on the basis of secure connection AccountManager. GetInstance (connection). CreateAccount (Localpart) from (" here to fill in the account id "), "" account password here, attributes ); // Create an account connection.login(" user ID here ", "account password here"); Connection.login (" Enter the user ID here ", "enter the account password here"); // Log in directlyCopy the code

Step 7: Client A receives the message code

ChatManager cm = ChatManager.getInstanceFor( connection ); Cm. addChatListener(new ChatManagerListener() {@override public void chatCreated(Chat Chat, boolean createdLocally ) { if( ! AddMessageListener (new ChatMessageListener() {@override public Void processMessage(Chat Chat, Message Message) {// Process the Message received here}}); }}});Copy the code

Step 8: Client B sends a plain text message code

ChatManager cm = ChatManager.getInstanceFor( connection ); //connection is created in step 6 Chat PC = null; Try {Chat PC = cm.createChat(jidCreate.entityBareFrom (" iD @host name ")); } catch(XmppStringprepException e) {e.prinintStackTrace (); } org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message(); Message.setbody (" Fill in the text message content here "); pc.sendMessage( message );Copy the code

At this point, messages are sent and received successfully. Here are some additional extensions

  • Receive offline messages (that is, the message sent to me by the other party after the local connection is closed and the connection is closed)

    OfflineMessageManager offlineManager = OfflineMessageManager.getInstanceFor(connection); / / connection is step 6 to create the List messageList = offlineManager. The getMessages (); // Return a list of offline messages

  • Set your online status (notify your friends if you want to change your current online status in real time)

    Presence userState = new Presence( Presence.Type.available ); userState.setStatus( “online” ); Connection. sendStanza(userState); //online indicates the online state and other states such as offline.

  • Listening for IM Connections

    Public class XmppConnectionListener implements ConnectionListener {@override public void connected(); XMPPConnection connection) {// Go to this callback after successful connection}

    @Override public void authenticated( XMPPConnection connection, Boolean resumed) {// Go to this callback if a connection is successfully certified} @override public void connectionClosed() {// Go to this callback if a connection is closed} @override public void ConnectionClosedOnError (Exception e) {// This is the callback after the connection is closed due to an error}Copy the code

    }

    connection.addConnectionListener(new XmppConnectionListener()); // Add the listener written above

  • Enable the automatic reconnection after disconnection

    ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor( connection ); . / / the connection is created step 6 reconnectionManager enableAutomaticReconnection (); / / open allows automatic reconnect reconnectionManager. SetReconnectionPolicy (reconnectionManager. ReconnectionPolicy. FIXED_DELAY); / / set a fixed time interval model reconnectionManager. SetFixedDelay (5); // Reconnect every 5 seconds

Please refer to my independently developed social APP, https://wesee.site, which uses Smack + OpenFire for single and group chat functions

If you are interested, I will continue to add a more detailed series of tutorials, you can add my new planet, when more than 100 people join, I will open source the relevant code