开发者

Simple issue with a thread

All I want to do is start a thread to listen for communication on a certain port.

I start this by having an 'ok' button on a jDialog. When 'ok' has been clicked, the jDialog should hide itself (HostClientDialog.setVisible(false);), which works when the thread start line isn't in there.

try {

            HostClientDialog.setVisible(false);

            // start a thread that listens for incoming messages
            new gameCycle().start();

} catch (Exception e) { }

The new gameCycle().start(); line is calling the following code:

public class gameCycle extends Thread {

    //public gameCycle(){
      //  super();
    //}

    @Override
    public void run() {

        try {

            ServerSocket connection = new ServerSocket(4242);

            // Wait for connection
            Socket s = connection.accept();

            // Socket input
            BufferedReader in = new BufferedReader(new
                    InputStreamReader(s.getInputStream()));

            // for receiving moves
            while (true) {

    开发者_运维百科            String message = "";

                message = in.readLine();

                if (message != null && !message.equals("")) {
                    // do something with message
                }

                sleep(100);

            } // end while

        } catch (Exception e) { }

    } // end run
} // end class

I understood the above code to be looping until a message is received, and then doing something with the message. But when you execute this code, the jDialog box is made again (instantly) and re-prompts the user to click ok. It won't let the user get past the jDialog box, it will just continually re-prompt them.

I'm fairly novice with threads (I haven't done much more than printing using multiple threads), so I feel like I might be me implementing it incorrectly. But I've looked around for examples, and they seem to be more or less what I have.

EDIT (11/29/2010 at 1:30 AM EST)

It seems that I don't quite have the idea of TCP communication down as well as I thought. My goal with the thread and subsequent while loop was as follows:

  • In the background the program would be waiting for any messages sent its way
  • If it it received a message it would update something on the GUI, and then go back to waiting for more messages

All the while allowing the user to be continually using the GUI.


I'd say the code you supplied, looks fine to me.

I would implement the possibility to cancel the whole thread instead of looping with while(true). Use a boolean instead and make the boolean accessible for other threads. If you need help on that, come back at me.

I think the problem lies with the code we do NOT see here. I'm partially interested in the code fragments surrounding the .start() call on your thread. What happens after that?

cheers

EDIT:

 public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    final JDialog dia = new JDialog();
    JButton btn = new JButton("Foo");
    btn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            dia.setVisible(false);
            Runnable t = new Runnable() {
                public void run() {
                    System.out.println("foo");
                }
            };
            t.run();
        }
    });
    dia.getContentPane().add(btn);
    dia.setSize(500, 400);
    dia.setVisible(true);
}
}

This works perfectly for me - sorry but I can't reproduce the error like you stated in the comments. Consider giving more code please :)

EDIT #2: Don't set any variables from within your thread directly. Instead make use of the observer-listener pattern. When there is a new message incoming, have the thread fire a propertyChangeEvent instead. http://download.oracle.com/javase/1.4.2/docs/api/java/beans/PropertyChangeListener.html

Maybe you should try and implement something more trivial .. go for a quick and easy chat first. http://www.ashishmyles.com/tutorials/tcpchat/index.html

When you have that down, think about your project ahead. Maybe reading on multithreading with swing might help? http://java.sun.com/developer/technicalArticles/Threads/swing/


Looks OK but I'm suspicious of that empty catch block. Or maybe that method is being invoked again?

Also if message == null you must exit the reading loop and close the socket, and the sleep is pointless: readline() will block if no data. And initializing 'message' is also pointless when you're about to assign it in the very next line.


I understood the above code to be looping until a message is received

Not quite. This line:

Socket s = connection.accept();

will block the execution thread until a connection is made. Are you sure that is happening? It might be that your program is simply sitting there waiting for a connection but none are being made (successfully anyway).

Maybe post some more info, like what the class requesting the connection looks like.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜