4

我一直在努力通过 Smack 和 Openfire 服务器与 XMPP 聊天。我的问题如下:

每当用户向另一个用户发送消息时,该消息都会在另一个用户处正确接收。但是任何回复都不会出现在第一条消息的发件人处。所以用户 1 成功发送给用户 2。然后,用户 2 无法向用户 1 发送任何回复。另一方面,如果我重新启动并让用户再次登录,用户 2 可以发送给用户 1,但反之则不行。

我想说的是,只有聊天的发起者可以发送消息,接收者不能回复。

我的代码看起来像这样

    package xmpp;


public class XMPPClient{

private static final int packetReplyTimeout = 500; // millis
private XMPPConnection connection;
private ChatManager chatManager;
private MessageListener messageListener;
private ConnectionConfiguration config;
private MyTimer t = MyTimer.getInstance();
private ArrayList<String> threadPool = new ArrayList<String>();

public XMPPClient()
{
    SmackConfiguration.setPacketReplyTimeout(packetReplyTimeout);

    //define openfire server information

    config = new ConnectionConfiguration("localhost",5222);
    config.setSASLAuthenticationEnabled(false);
    config.setSecurityMode(SecurityMode.disabled);

    connection = new XMPPConnection(config);

    //connect to server
    t.start("Connecting to server...");
    try {
        connection.connect();
    } catch (XMPPException e) {
        System.err.println("Failed to connect to server! Connect to VPN!\t"+e.getMessage());
        System.exit(0);
    }
    t.end("Connection took ");

    //setup chat mechanism
    chatManager = connection.getChatManager();
    chatManager.addChatListener(
            new ChatManagerListener() {
                @Override
                public void chatCreated(Chat chat, boolean createdLocally)
                {
                    if (!createdLocally)
                        chat.addMessageListener(new MyMessageListener());
                }
    });
}
public boolean login(String userName, String password, String resource) {       
    t.start("Logging in...");
    try {
        if (connection!=null && connection.isConnected()) 
            connection.login(userName, password, resource);
        //set available presence
        setStatus(true);
    } 
    catch (XMPPException e) {
        if(e.getMessage().contains("auth")){
            System.err.println("Invalid Login Information!\t"+e.getMessage());
        }
        else{
            e.printStackTrace();
        }
        return false;
    }
    t.end("Logging in took ");
    return true;
}
public void setStatus(boolean available) {
    if(available)
        connection.sendPacket(new Presence(Presence.Type.available));
    else
        connection.sendPacket(new Presence(Presence.Type.unavailable));
}

public void sendMessage(String message, String buddyJID) throws XMPPException {
    System.out.println(String.format("Sending mesage '%1$s' to user %2$s", message, buddyJID));
    boolean chatExists = false;
    Chat c = null;
    for(String tid : threadPool)
    {
        if((c = chatManager.getThreadChat(tid)) != null)
        {
            if(c.getParticipant().equals(buddyJID))
            {
                if(checkAvailability(buddyJID))
                {
                    chatExists = true;
                    break;
                }
                else
                {
                    threadPool.remove(tid);
                    break;
                }
            }
        }
    }
    if (chatExists)
    {
        Chat chat = c;
        chat.sendMessage(message);
    }
    else
    {
        Chat chat = chatManager.createChat(buddyJID, messageListener);
        threadPool.add(chat.getThreadID()); System.out.println(chat.getThreadID());
        chat.sendMessage(message);
    }
}

public void createEntry(String user, String name) throws Exception {
    System.out.println(String.format("Creating entry for buddy '%1$s' with name %2$s", user, name));
    Roster roster = connection.getRoster();
    roster.createEntry(user, name, null);
}

public boolean checkAvailability(String jid)
{
    System.out.print("Checking availability for: "+jid+"=");
    System.out.println(connection.getRoster().getPresence(jid).isAvailable());
    return connection.getRoster().getPresence(jid).isAvailable();
}

public void disconnect() {
    if (connection!=null && connection.isConnected()) {
        setStatus(false);
        connection.disconnect();
    }
}

}

import org.jivesoftware.smack.packet.Message;

public class MyMessageListener implements MessageListener {
@Override
public void processMessage(Chat chat, Message message) {
    String from = message.getFrom();
    String body = message.getBody();
    System.out.println(String.format("Received message '%1$s' from %2$s", body, from));
}

}

我不确定问题是什么。有什么建议么?示例代码?

谢谢 <3

4

3 回答 3

2

我不确定这是否会对您有所帮助,但我可以使用以下代码得到回复:

public void chat(String AddressedUser) throws NotConnectedException {
    //Create username whom we want to send a message
    String userToSend = AddressedUser + "@" + serverDomain;

    ChatManager chatmanager = ChatManager.getInstanceFor(connection);
    Chat newChat = chatmanager.createChat(userToSend , new MessageListener() {
        @Override
        public void processMessage(Chat chat, Message message   ) {
            // TODO Auto-generated method stub
            System.out.println("Received message: " + message);

        }
    });

    try {
        newChat.sendMessage("Hey");
    }
    catch (XMPPException e) {
        System.out.println("Error Delivering block");
    }

}

我正在发送“嘿”,然后其他用户写的内容我将在我的 logcat 中看到。

于 2014-12-09T16:36:26.347 回答
1

您尚未指定接收器是什么,例如,它是现有客户端(例如 Spark)还是更多自定义代码。这会很有帮助,就像知道您使用的是什么版本的 Smack 一样。

该特定代码有几个问题。

  • 它不断为发送的每条消息创建新的聊天对象,而不是简单地重复使用相同的聊天。
  • 没有注册ChatManagerListener来处理与现有聊天无关的新聊天消息。
于 2012-05-30T14:39:23.030 回答
0

这是代码非常复杂,似乎只是为了发送消息。这是一个在发送和接收方面都能完美运行的示例代码:

http://www.javaprogrammingforums.com/java-networking-tutorials/551-how-write-simple-xmpp-jabber-client-using-smack-api.html

于 2012-05-30T13:12:41.493 回答