java – 使用smack API发送和接收消息
作者:互联网
我已经在本地计算机上设置了我的开火(jabber服务器),其中有两个用户testuser1和testuser2.使用Spark客户端,两个用户都可以毫无问题地进行聊天,这很不错.
openfire IP -192.168.1.65
我想使用smack API(3.3.0)发送和接收消息.我已经写了发送方端代码来发送消息(使用testuser1)并在testuser2端接收到Spark客户端(带有testuser2)消息进行测试,但是当我尝试使用java代码接收发送方消息时,我无法接收这些发布消息.
Sender.java
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.MessageListener;
public class Sender
{
public static void main(String a[]) throws XMPPException, InterruptedException
{
XMPPConnection connection = new XMPPConnection("192.168.1.65");
System.out.println(connection);
connection.connect();
connection.login("testuser1", "test123");
Chat chat = connection.getChatManager().createChat("testuser2@sameek", new MessageListener() {
public void processMessage(Chat chat, Message message) {
// Print out any messages we get back to standard out.
System.out.println("Received message: " + message);
}
});
chat.sendMessage("Howdy test1!");
while (true) {
Thread.sleep(50);
}
}
}
Receiver.java
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.MessageListener;
public class Receiver
{
public static void main(String a[]) throws XMPPException,, InterruptedException
{
XMPPConnection connection = new XMPPConnection("192.168.1.65");
System.out.println(connection);
connection.connect();
connection.login("testuser2", "test123");
Chat chat = connection.getChatManager().createChat("testuser1@sameek", new MessageListener() {
public void processMessage(Chat chat, Message message) {
// Print out any messages we get back to standard out.
System.out.println("Received message: " + message);
}
});
chat.sendMessage("Howdy test2!");
while (true) {
Thread.sleep(50);
}
}
}
请帮助我,并建议我是否遵循错误的方法.
谢谢
解决方法:
在按照这里的教程(http://www.javacodegeeks.com/2010/09/xmpp-im-with-smack-for-java.html)后我遇到了类似的问题,这就是我发现的:
当您创建聊天时,您将与要连接的用户聊天(例如,在我的情况下为“user1 @ gbd038”).如果user1使用诸如Spark之类的GUI客户端(可能具有内置支持和/或错误处理),并且user1将接收消息,则此方法正常工作.此过程将messageListener附加到现在与“user1 @ gbd038”关联的聊天中.但是,当我作为user1从Spark回复时,smack收到的聊天实际上是通过location标记完成的,例如:
Received message 'hi' from user1@gbd038/Spark 2.6.3
因此,它会创建一个应用程序未侦听的新聊天(因此您的应用程序将不会接收/打印出来).我找到了两种方法来解决这个问题:
>在开始对话时使用位置标记(虽然这看起来不太可扩展或不健壮):
xmppManager.sendMessage(“Hello mate”,“user1 @ gbd038 / Spark 2.6.3”);
>正如Robin建议的那样,使用ChatManagerListener(当收到user1的回复时会创建一个新的聊天,可以转发给messageListener):
chatManager = connection.getChatManager();
messageListener = new MyMessageListener();
chatManagerListener = new ChatManagerListener() {
@Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(messageListener);
}
};
chatManager.addChatListener(chatManagerListener);
希望能帮助某人处于同一位置!
标签:smack,openfire,java,xmpp 来源: https://codeday.me/bug/20191007/1868673.html