0

I have this simple networking code (I'm trying to implement a simple chat server as an exercise),but I'm stuck and I can't figure out what's happening. I create the GUI for my client and it has an instance of another class that carries out all the necessary operations to connect and send/receive message to my server.

package com.luca.chat;

import java.awt.*
import java.awt.event.*
import javax.swing.*

class Window extends JFrame {

  private final static int WIDTH=500;
  private final static int HEIGHT=300;

  private String status="disconnected";

  private JPanel panel;
  private JTextArea area;
  private JTextField field,address;
  private JButton button;
  private JLabel label;

  private IOClass io=new IOClass(this);

  Window() {
    super("Chit-Chat");
    setSize(new Dimension(WIDTH,HEIGHT));
    ImageIcon icon=new ImageIcon("..\\images\\lucas.png");
    setIconImage(icon.getImage());

    JPanel contentPane=(JPanel)getContentPane();

    // add the text area to display incoming and outgoing messages
    area=new JTextArea();
    area.setEditable(false);
    contentPane.add(area,BorderLayout.CENTER);

    // add text field to send messages
    field=new JTextField(20);
    field.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent e) {
        String message=field.getText();
        io.send(message);
        field.setText("");
      }
    });
    panel=new JPanel();
    panel.add(field);
    panel.setBorder(BorderFactory.createEtchedBorder());
    contentPane.add(panel,BorderLayout.SOUTH);

    // add status bar on top 
    label=new JLabel("status: "+status);  
    address=new JTextField(15);
    button=new JButton("connect");
    panel=new JPanel();  
    panel.add(label);
    panel.add(address);
    panel.add(button);  
    button.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        io.connect(address.getText());
      }
    }); 
    panel.setBorder(BorderFactory.createEtchedBorder());
    contentPane.add(panel,BorderLayout.NORTH);

    Toolkit kit=getToolkit();
    Dimension dim=kit.getScreenSize();
    setLocation((dim.width-WIDTH)/2,(dim.height-HEIGHT)/2);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);

    loop();
  }

  void loop() { 
    while (true) 
      if (io.connected) 
        io.receive(); 
      else            // if I comment this line out it never calls receive() ?????    
        System.out.println("????"); 
  }

  void setStatus(String status) {
    label.setText(status);
  }

  void setText(String received) {
    area.append(received);
  }

  public static void main(String[] args) {
    new Window();
  }


}

the IOClass has all the methods to connect/send/receive (I think it acts like something of a controller? I don't know,I'm just beginning to learn this patterns) an a flag,that controls whether the connection is estabilished or not. If there's a connection, it calls the receive method,which is an infinite loop to listen to incoming messages.

But if I leave just the if statement (inside loop()) without an else... it doesn't execute! I mean.. the while loop never starts (I tried with some prints..it never gets there) but it gets there if I add an else!

for example,this blocks at the if statement:

 void loop() { 
   while (true) 
     if (io.connected) 
       io.receive(); 
 }

this works (the while loops forever):

 void loop() { 
   while (true) 
     if (io.connected) 
       io.receive();   
     else
        ....do something else...
 }

or even this works:

 void loop() {
   while (true) { 
     System.out.println("whatever"); 
     if (io.connected) 
       io.receive();
   }  // end of while
 }

I can't understand,this seems a very odd behaviour to me.

EDIT: using Eclipse's debug feature I see that when it works the while loop loops forever as intended, when it doesn't it just BLOCKS at the if condition

11
  • That is not true. The if statement will still execute. If I understood your question correctly you could cut almost all of the code above away and still have all the information required to ask this question. Oct 31, 2015 at 11:30
  • @user2651804 no,it won't.. Even when the connection method in the IOClass sets the flag to true
    – Luca
    Oct 31, 2015 at 11:33
  • The most important thing in questions like this is providing a short example that compiles and demonstrates your problem. I suggest you fully paranthesize your while-loop and if-else. It might solve problems that you're having. Oct 31, 2015 at 11:36
  • 1
    You have an infinite loop constantly checking for the connedted flag. This is not how you should do things. Instead, the ActionListener should start thread that connects, and then starts receiving data.
    – JB Nizet
    Oct 31, 2015 at 11:37
  • @JBNizet yes,I know this is not the correct way to do it...but I would like to know why this is happening.If I insert whatever statement in the while loop it executes,otherwise it doesn't! for example if i write: void loop() { while (true) System.out.println("whatever"); if (io.connected) io.receive(); } it works.. It doesn't make sense to me at all
    – Luca
    Oct 31, 2015 at 11:56

2 Answers 2

0
void loop() { 
    while (true) 
      if (io.connected) 
        io.receive(); 
      else  // if I comment this line out it never calls receive() ?????    
        System.out.println("????"); 
}

In the example of your answer, you point to this code as the culprit. Since the while doesn't have brackets {} Only the next line will be considered the body of the while loop. The same goes for if without brackets: Only the first line in the true condition will execute. It may or may not be followed by an else-clause.

In your case, since the next line after your while is an if-else and both conditions only have 1 line to execute, your while loop works as intended.

If what you meant to say is this:

void loop() { 
    while (true) 
      if (io.connected) 
        io.receive(); 
      //else   
        System.out.println("????"); 
}

Then this wouldn't compile, since you are telling System.out.println("????"); to execute AFTER the while loop is done and the condition of the while-loop is explicitly true; The code will never be reached. If you use a variable as the flag instead, it will compile and you will experience that System.out.println("????"); will execute once, when the loop is done.

1
  • no, you got it wrong. Maybe I wasn't clear enough. let me edit my question
    – Luca
    Oct 31, 2015 at 12:34
0

With the help of Eclipse debugger,going step by step,I was able to find the catch. Since when I instantiate a JFrame,the JVM automatically spins a new thread (the Event queue), and since it is the ActionListener registered with the connection button that calls the connect() method that sets the boolean flag to true, the flag is true in this one thread, but in the main thread it is still false, so the if condition never evaluates to true,hence, I hang waiting for the receive() method to be called,and I get no output on screen. Using the volatile modifier solves the problem, so the updated variable is automatically visible to all threads. Since I'm new to threads, this wasn't so obvious.. but a comment put me in the right direction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.