Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8997821
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T23:56:27+00:00 2026-06-15T23:56:27+00:00

I have developed a simple chat client which sends and receives messages as well

  • 0

I have developed a simple chat client which sends and receives messages as well as user typing CHatState notificationbetween 2 users – userx and usery. In the debug window I see the packets either containing body or with the chatstate. All the packets are being logged correctly.

Problem 1 : But my window is showing both in the chat(JLabel). Because of this, Whenever a user starts typing, the other user sees a null message in his window, which is actually a packet containing the chat state notification without any body. I have tried various conditions, but all have failed. I tried the following ridiculous if condition, yet it displays the null packets.

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

Problem 2: I’m unable to log the notification chat states which are sent. My code goes as follows :

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

    }

}

Details:
Normal message packets are like this :

<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>

Chat State packets are like this :

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

Screenshot :
enter image description here

Any comments?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T23:56:27+00:00Added an answer on June 15, 2026 at 11:56 pm

    1) You are right, that condition is ridiculous, and very wrong.

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

    There will always be a message passed in, thus message will never be null and this condition will always pass, which is a good thing since it will throw a NPE if the body is null.

    What you are trying to do is this:

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

    All the other checks are either uneccessary or redundant.

    2) You don’t actually create your ChatStateListener or register it with the Chat (addMessageListener). That is why you don’t receive the chat state messages.

    In addition to these, you are creating a new Chat every time you send a message or the DocumentListener is called. I don’t think this is what you actually want. I would think you want to send and receive on the same Chat.

    Hints and Tips

    There are also a lot of glaring issues with your code with respect to coding standards so I will also add some tips (please don’t take this as an insult, I am simply trying to help you with your Java skills).

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

    should be

    if (!<boolean condition>)
    

    for example

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

    should be

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

    Also
    if ( == true)

    should be

    if (<boolean condition>)
    
    • Don’t mix your inner classes with methods, either put them all before
      or after.
    • Class names ALWAYS start with a capital letter.
    • Don’t use static variables for instance based data.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm a junior .net developer.I have developed a simple client application (.net3.5) which needs
I have developed a simple location aware iPhone application which is functionally working very
I have developed a simple GWT application with the client/server packages. From server package
I have developed a simple server using Tomcat which runs a servlet. The servlet
I have developed a simple utility for my iPhone and iPad apps which places
I have developed a simple batch file which I want to set up as
I have developed a simple NFC app which will launch after sensing the NFC
I have developed a simple application using SDK(Android: 3.2[API-13]) for, to display Google banners.
I have developed a simple library in Ruby and need to use this in
I am new to rails and have developed a simple rails application on my

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.