建立聊天會話併傳送訊息
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();
}