0

メッセージを送受信するだけでなく、ユーザーが 2 人のユーザー (userx と usery) の間で CHatState 通知を入力する単純なチャット クライアントを開発しました。デバッグ ウィンドウに、本文を含むパケットまたはチャット状態を含むパケットが表示されます。すべてのパケットが正しくログに記録されています。

問題1:しかし、私のウィンドウはチャット(JLabel)に両方を表示しています。このため、ユーザーが入力を開始するたびに、他のユーザーのウィンドウに null メッセージが表示されます。これは、実際には本文のないチャット状態通知を含むパケットです。さまざまな条件を試しましたが、すべて失敗しました。次のばかげた if 条件を試しましたが、null パケットが表示されます。

if (message != null || message.getBody().isEmpty() == false
                    || message.getBody() != null
                    || message.getBody().toString().compareTo("null") == 1
                                            && message.getError() == null)

問題 2:送信された通知チャットの状態をログに記録できません。私のコードは次のようになります:

import java.applet.Applet;

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("<html>");
    static Chat chat;
    String message;
    static ChatState status;
    static String to;
    static boolean flag = false;
    JLabel typingStat;

    public class typingStatus implements ChatStateListener {

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

            System.out.println(arg1.name());

        }

        @Override
        public void processMessage(Chat arg0, Message arg1) {
            // TODO Auto-generated method stub
            System.out.println(arg1.getBody());

        }

    }

    public void sendChat(String msg) {
        try {
            to = "harsh00008";
            if (username.compareTo(to) == 0)
                to = "usery@xyz";
            else
                to = "userx@xyz";

            chat = connection.getChatManager().createChat(to, this);

            chat.sendMessage(msg);
        } catch (XMPPException e) {

            e.printStackTrace();
        }

    }

    public void changeStatus() {
        // TODO Auto-generated method stub
        if (username.compareTo("harsh00008") == 0)
            chat = connection.getChatManager().createChat("test@prc.p1.im",
                    this);
        else
            chat = connection.getChatManager().createChat(
                    "harsh00008@prc.p1.im", this);

        if (textField.getText().isEmpty() == false && flag == false) {
            try {
                ChatStateManager.getInstance(connection).setCurrentState(
                        ChatState.composing, ChatBoard.chat);

                flag = true;
            } catch (XMPPException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } else {
            if (textField.getText().isEmpty() == true && flag == true) {
                try {
                    ChatStateManager.getInstance(connection).setCurrentState(
                            ChatState.paused, ChatBoard.chat);

                    flag = false;
                } catch (XMPPException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

        }

    }

    public ChatBoard(String user, String pass) {

        setVisible(true);

        username = user;
        password = pass;

        //JFRAME CREATION CODE OMITTED



        textField.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                // TODO Auto-generated method stub
                changeStatus();

            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                // TODO Auto-generated method stub
                changeStatus();

            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                // TODO Auto-generated method stub
                changeStatus();

            }
        });


        sendButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (textField.getText().isEmpty() == false) {
                    sendChat(textField.getText().toString());
                    board.setText(board.getText() + "<br>me : "
                            + textField.getText());
                    changeStatus();
                    textField.setText("");
                }

            }
        });

        JLabel info = new JLabel("Press Enter or click");

        JButton exit = new JButton("Exit");
        exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                WelcomeUser w = new WelcomeUser();
                connection.disconnect();
                w.setVisible(true);
            }
        });


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

        XMPPConnection.DEBUG_ENABLED = true;

        ConnectionConfiguration config = new ConnectionConfiguration(
                "prc.p1.im", 5222, "prc.p1.im");

        connection = new XMPPConnection(config);

        try {
            connection.connect();

        } catch (XMPPException e) {

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

        try {
            connection.login(username, password);

        } catch (XMPPException e) {

            flag = false;

            textField.setVisible(false);
            sendButton.setVisible(false);

            info.setText("Invalid Login!");

            welcomeLabel.setText("Invalid user!");

        }

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

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

                chat.addMessageListener(new MessageListener() {

                    public void processMessage(Chat chat, final Message message) {
                        try {
                            SwingUtilities.invokeAndWait(new Runnable() {

                                @Override
                                public void run() {

                                    String sender = message.getFrom();
                                    if (username.compareTo("usery") == 0)
                                        sender = "h";
                                    else
                                        sender = "t";

                                    if (message != null
                                            || message.getBody().isEmpty() == false
                                            || message.getBody() != null
                                            || message.getBody().toString()
                                                    .compareTo("null") == 1
                                            && message.getError() == null)
                                        board.setText(board.getText()
                                                + "<br> <font color=red>"
                                                + sender
                                                + " </font>:<font color=black> "
                                                + message.getBody() + "</font>");
                                    URL url = getClass().getResource(
                                            "resource/ultrakill_ultimate.wav");
                                    AudioClip clip = Applet.newAudioClip(url);
                                    clip.play();
                                }
                            });
                        } catch (InvocationTargetException e) {

                            e.printStackTrace();
                        } catch (InterruptedException e) {

                            e.printStackTrace();
                        }

                    }

                });

            }

        });

    }

    @Override
    public void processMessage(Chat arg0, Message arg1) {

        message = arg1.getBody();
        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {

                }
            });
        } catch (InvocationTargetException e) {

            e.printStackTrace();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

    }

}

詳細: 通常のメッセージ パケットは次のようになります。

<message id="5KE6T-11" to="usery@xyz" from="userx@xyz/Smack" type="chat">
  <body>hi people</body>
  <thread>fqw5912</thread>
  <active xmlns="http://jabber.org/protocol/chatstates"/>
</message>

チャット状態パケットは次のようになります。

<message id="IgIbv-13" to="userx@xyz" from="usery@xyz/Smack" type="chat">
  <thread>fqw5913</thread>
  <composing xmlns="http://jabber.org/protocol/chatstates"/>
</message>

スクリーンショット: ここに画像の説明を入力

コメントはありますか?

4

3 に答える 3

2

1)あなたは正しいです、その状態はばかげており、非常に間違っています。

if (message != null || message.getBody().isEmpty() == false
                        || message.getBody() != null
                        || message.getBody().toString().compareTo("null") == 1
                                                && message.getError() == null)

渡されるメッセージは常に存在するため、メッセージがnullになることはなく、この条件は常に渡されます。これは、本文がnullの場合にNPEをスローするためです。

あなたがしようとしていることはこれです:

if (message.getBody() != null)  // getBody() returns null if there is no body so check for empty is unnecessary.

他のすべてのチェックは、不必要または冗長です。

2)実際にChatStateListenerを作成したり、チャットに登録したりすることはありません(addMessageListener)。そのため、チャット状態のメッセージは受信されません。

これらに加えて、メッセージを送信するか、DocumentListenerが呼び出されるたびに、新しいチャットを作成します。これはあなたが実際に望んでいることではないと思います。同じチャットで送受信したいと思います。

ヒントとコツ

また、コーディング標準に関してコードには明白な問題がたくさんあるので、いくつかのヒントも追加します(これを侮辱として受け取らないでください。私は、Javaスキルを支援しようとしているだけです)。

if (<boolean condition> == false) // It is already evaluated to true or false

する必要があります

if (!<boolean condition>)

例えば

if (message.getBody().isEmpty() == false)

する必要があります

if (!message.getBody().isEmpty())

また、(== true)の場合

する必要があります

if (<boolean condition>)
  • 内部クラスをメソッドと混合しないでください。すべてを前または後に配置してください。
  • クラス名は常に大文字で始まります。
  • インスタンスベースのデータに静的変数を使用しないでください。
于 2012-12-14T19:37:56.980 に答える