创建聊天会话并发送消息

Smack(Java)

  • 使用 Smack 4.1
  • 建议在项目中包含 Smack 作为 Maven 依赖项(例如,使用 gradle 或 Maven)。
  • 另外,必须手动将以下 Smack 工件/ jar 添加到类路径中:smack-core,smack-extensions,smack-experimental,smack-im,smnack-tcp,smack-java7
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

public void sendMessage() {

XMPPTCPConnectionConfiguration config = 
  XMPPTCPConnectionConfiguration.builder()
            .setServiceName("mydomain.local")
            .setHost("127.0.0.1")
            .setPort(5222)
            .build();

XMPPTCPConnection connection = new XMPPTCPConnection(config);

connection.connect();
connection.login("test1", "test1pwd"); 

ChatManager chatManager = ChatManager.getInstanceFor(connection);
String test2JID = "test2@domain.example";
Chat chat = chatManager.createChat(test2JID);
chat.sendMessage("Hello, how are you?");

connection.disconnect();
}