views:

177

answers:

2

I want to make a chat which will be programed in java. one computer will host the server and the other one will initiate the socket [tcp port]. now from what I read there should be a loop that will constantly read the socket which means it will make the code stuck. I have a button that is 'actionperformed' on mouse release, I want to know if it will work along with the loops that constantly reads the socket so that it will also send the infromation I wrote.

If I must thread it, I want to know if the run() method must be void because if I thread it it will mean creating a new class, and the whole GUI is one big class which includes a text area, and it's private. also how can I extract the information from the socket directly to the text area? lets say the textarea variable is called "chatOutput".

thx :)

+1  A: 

I presume that this is your situation:

You have a GUI with a text area for typing in chat messages, and a button that will submit new messages to the chat room. You want to keep some panel updated with the stream of chat messages by looping on the Socket's InputStream, but also want to be able to write to the Socket's OutputStream while the InputStream is being looped upon.

This would be my suggestion for the client side code:

Socket con = new Socket(host, port);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
PrintWriter out = new PrintWriter(con.getOutputStream(), true);
...
Thread t = new Thread(new Runnable() {
    public void run() {
        while(con.isConnected()) {
            String line = in.readLine();
            // update your chat panel with line
        }
    }
});
t.start();
...

And in your action:

...
out.println(/*contents of the text box*/);
// clear contents of text box
// ?update panel?
...
Finbarr
you'll want to make sure that when the update to the chat panel is performed it is done on the gui thread to prevent any undefined behavior.
luke
+1 @luke: Good point. Conveniently, the `append() method of `JTextArea` is thread safe, as seen in this example: http://groups.google.com/group/comp.lang.java.help/msg/9f7f86db103f35c9
trashgod
A: 

oh, I didn't know u can just write "new runnable" in the thread creation, I thought u need to make a new class and implement runnable. thx allot :) !

raven
@raven: Welcome to StackOverflow. Thoughtful comments like this may be added to the relevant answer. Also, consider accepting (green check mark) and/or up-voting (orange triangle) @Finbarr's useful answer.
trashgod