Tuesday, May 3, 2016

XMPP chat Java client with smack

XMPP Chatting

1. Connection
2. Register User
3. Login
4. Display user list
5. Send message
6. Change password
7. disconnect


import java.io.IOException;
import java.util.Collection;

import org.jivesoftware.smack.AccountManager;
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.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class ChatClient implements {

XMPPConnection connection;

public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration cc = new ConnectionConfiguration("127.0.0.1", 5222, "127.0.0.1");

connection = new XMPPConnection(cc);
try {
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(userName, password, "resource");// Login
System.out.println(connection.isAuthenticated());

} catch (Exception e) {

}

}

public void addUser(String userName, String password) throws XMPPException {
AccountManager accountManager = new AccountManager(connection);
try {
accountManager.createAccount(userName, password); // Create User
System.out.println("User Created");
accountManager.changePassword("12345"); // Change password
} catch (XMPPException e1) {
System.out.println(e1.getMessage());
}

}

public void changePassword(String password) throws XMPPException {
AccountManager accountManager = new AccountManager(connection);
try {
accountManager.changePassword("12345"); // Change password
System.out.println("Password Changed");

} catch (XMPPException e1) {
System.out.println(e1.getMessage());
}

}

public void sendMessage(String message, String to) throws XMPPException {
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}

public void displayBuddyList() {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();

System.out.println("\n\n" + entries.size() + " buddy(ies):");
for (RosterEntry r : entries) {
System.out.println(r.getUser());
}
}

public void disconnect() {
connection.disconnect();
}



public static void main(String args[]) throws XMPPException, IOException {
ChatClient c = new ChatClient();
String msg = "hello";
XMPPConnection.DEBUG_ENABLED = false;
c.addUser("hswain", "12345");
c.login("hswain@127.0.0.1", "12345");
c.displayBuddyList();
c.sendMessage(msg, "test@127.0.0.1"); // Send Message
c.changePassword("54321");
c.disconnect();
System.exit(0);
}


}

No comments:

Post a Comment

How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...