无法在JAVA中使用SMACK api显示收到的消息

时间:2012-12-13 10:41:59

标签: java smack

我在localhost上使用SMACK api和OpenFire创建了一个简单的客户端。截至目前,我有两个用户说X和Y.每当有人登录到客户端时,都会有一个发送按钮向用户Y发送消息。我检查了XMPP调试管理器,我能够发送/在那里收到消息。但是,我无法在JLabel中显示那些我用于显示消息的消息。如果用户Y按下发送按钮,则根据功能向他自己发送消息并在JLabel上显示。但是当用户X点击发送按钮时,会收到消息,但不会在Y的JLabel上显示/更新消息。

有趣的是,一切都按照gtalk配置的方式工作。

结构如下:

WelcomeUser.java: 是带有用户名和密码提示的欢迎表单。在点击登录按钮时: 它将ChatBoard类设置为可见,并将用户名密码传递给ChatBoard的构造函数。 代码:

chBoard=new ChatBoard(username.getText(),password.getText());
                chBoard.setVisible(true);
                setVisible(false);

以下是ChatBoard.java的代码:

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

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

public class ChatBoard extends JFrame implements MessageListener {

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    static String username, password;
    static XMPPConnection connection;
    private JTextField textField;
    static JLabel board = new JLabel("");
    static Chat chat;

    public void sendChat() {
        try {
            chat = connection.getChatManager().createChat(
                    "userY@my-pc/Smack", this);
            chat.sendMessage("Hello, This is " + username);
        } catch (XMPPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    /**
     * Create the frame.
     */
    public ChatBoard(String user, String pass) {

        username = user;
        password = pass;

        ////  
                   ///JFrame creation code ommited for this thread.
        // ////////////////////////////////////////////

        XMPPConnection.DEBUG_ENABLED = true;

        ConnectionConfiguration config = new ConnectionConfiguration(
                "127.0.0.1");


        connection = new XMPPConnection(config);

        try {
            connection.connect();
            System.out.println("Connected...");
        } catch (XMPPException e) {

            e.printStackTrace();
            System.out.println("Not Connected. Error :" + e.getMessage());
        }

        try {
            connection.login(username, password);
            System.out.println("Logged in...");
        } catch (XMPPException e) {

            e.printStackTrace();
            System.out.println("Not Logged in. Error :" + e.getMessage());
        }

        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());
        }

        // /////////////////////////////////

    }

    @Override
    public void processMessage(Chat arg0, Message arg1) {
        // TODO Auto-generated method stub

        board.setText(board.getText() + arg1.getBody());
        System.out.println(arg1.getFrom() + ":" + arg1.getBody().toString());

    }

}

我是新手,所以如果有任何愚蠢的错误,请原谅我。非常感谢您的帮助。

混杂。详细信息:使用SMACK 3.2.2在localhost上的OpenFire 3.7.1

3 个答案:

答案 0 :(得分:1)

查看http://www.igniterealtime.org/builds/smack/docs/latest/documentation/messaging.html的底部。对于来自其他用户的传入聊天,您必须覆盖ChatManagerListener

你可以在processMessage上设置一个断点并且它是否达到了断点?如果是这样,那可能只是确保:

board.setText()

发生在Swing event dispatch thread

所以尝试像这样制作你的processMessage:

@Override
public void processMessage(Chat arg0, Message arg1) {
    // TODO Auto-generated method stub

    try
    {
        SwingUtilities.invokeAndWait(new Runnable()
        {

            @Override
            public void run()
            {
                board.setText(board.getText() + arg1.getBody());
            }
        });
    }
    catch (InvocationTargetException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(arg1.getFrom() + ":" + arg1.getBody().toString());

}

答案 1 :(得分:0)

我在chatBoard中添加了这个代码,只是在我的代码中提到的构造函数的末尾,它现在似乎工作了:-)谢谢alex.p!

connection.getChatManager().addChatListener(new ChatManagerListener() {



                public void chatCreated(final Chat chat, final boolean createdLocally) {

                    chat.addMessageListener(new MessageListener() {



                        public void processMessage(Chat chat, Message message) {

                            //JOptionPane.showMessageDialog(null, "Rec: For " + chat.getParticipant() + " from " + message.getFrom() + "\n" + message.getBody());

                            String sender=message.getFrom();

                            String senderNames=sender;

                            System.out.println("Received message: " + (message != null ? message.getBody() : "NULL"));

                            board.setText(board.getText()+"\n "+ message.getFrom()+" : "+ message.getBody());
                            //PrivateChatManager.receiveMessage(sender, senderNames, message.getBody());



                        }

                    });

                }
        });

答案 2 :(得分:0)

希望此代码可以为您提供帮助:

public void processMessage(Chat aChat, Message aMessage) {

    final XmppBot bot = this.xmppBot;
    final Chat chat = aChat;
    final Message message = aMessage;

    log.debug("message received, type {}", message.getType().toString());


    if (message.getBody() != null) {

        Runnable runnable = new Runnable() {

            public void run() {

                Thread.currentThread().setName("Chat: "+chat.getParticipant()+ " Message: "+ message.getBody());

                PrintWriter threadPrintWriter = null;

                threadPrintWriter = new PrintWriter(new ChatWriter(chat));

                bot.getContext().setChat(chat);
                bot.getContext().setPrintWriter(threadPrintWriter);

                bot.processCommand(message.getBody());

                bot.getContext().removeMultiUserChat();
                bot.getContext().removePrintWriter();

            }
        };

        Thread t = new Thread(runnable);
        t.start();
    }

}