How to Send message from one user to other ( chat example) In xmpp

We have knew how to add roster in xmpp server . Now we will send message from one user to other.
There is simple example for creating chat. There we will send a message using smack api and xmpp server. You can can visit how to install xmpp server.

package com.javaproficiency.demo;

import java.util.Collection;

import org.jivesoftware.smack.Chat;
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;

public class SendMessageInChat {

public static void main(String[] args) {

AddRoster addRoster = new AddRoster();

XMPPConnection connection = addRoster.Connect();
try {
connection.login(“yogesh@www.javaproficiency.com”,”123″);
System.out.println(“Login”);

Chat chat = connection.getChatManager().createChat(“shivam@www.javaproficiency.com”, new MessageListener() {

@Override
public void processMessage(Chat chat, Message message) {
// Print out any messages we get back to standard out.
System.out.println(“Received message: ” + message);
}

});
try {
chat.sendMessage(“How are you dear !!”);
System.out.println(” Send Message succesfully”);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

connection.disconnect();

} catch (XMPPException e) {

e.printStackTrace();
}
}

private void loginUser(XMPPConnection connection) {
// TODO Auto-generated method stub

}

public XMPPConnection Connect() {

ConnectionConfiguration config = new ConnectionConfiguration(
“localhost”, 5222);

/*
* ConnectionConfiguration config = new ConnectionConfiguration(
* “192.163.2.200”, 5222);
*/
XMPPConnection connection = new XMPPConnection(config);
try {
connection.connect();
} catch (XMPPException e) {

e.printStackTrace();
}
return connection;
}

}

After execution of this you can see message in xmpp client spark as
How to chat in xmpp server

2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

56 − 48 =