global chat server program design

I'm trying to make a chat program where the client sends a message to the server which the server redirects it back to all (global) the connected clients.   I have tested out the program using data input/output streams and basically modelled it off of other bits and pieces out there to see if it works.   In fact it worked alright, but now I'm using java nio package (buffers and channels) instead of streams and having trouble making connections successfully.   My problem is, that when I try to read data from a channel, it gets a NotYetConnectedException and I'm assuming this is due to a SocketChannel not being connected at the time of the read() operation.   Although the class design structure worked for the data input/output streams version, it seems that how it's designed is causing this problem.   So I want to know exactly in what order the methods are called (even I follow most of it, when I test the code, I don't get why the Client() constructor is called twice, etc.), and if necessary, what would be a better way to structure these classes to make the connection successful.   I'll post what I have and mark the part where that's causing the NotYetConnectedException.   It basically makes the server spawn a ServerThread for every socket that connects to, and the client runs a background thread (Client extends Thread) for receiving any messages sent back from the server.   The input is retrieved from the user interface (GUI) and the event is handled for this string message.   Any comments and suggestions are appreciated.  

(Also, this program works by first running the server (java Server 5000) and then the client with the port that it's trying to connect to (java Client 5000)... and I'm not too worried about its performance at this point since I just want to see if this works.   Thanks.)

-----------------------------Server.java----------------------------------
import java.awt.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;

public class Server {

    private ServerSocketChannel ssc;
    private ServerSocket ss; // the ServerSocket that is used for accepting new connections
    //private Hashtable outputChannels = new Hashtable();
    private LinkedList outputChannels = new LinkedList();
    private SocketChannel sc;
    private ByteBuffer buffer = ByteBuffer.allocate(50); // default capacity
    private Charset charset = Charset.forName("US-ASCII");
    private CharsetEncoder encoder = charset.newEncoder();

    public Server(int port) throws IOException {
        listen(port); // all that is done is to listen
    }

    private void listen(int port) throws IOException {

        ssc = ServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(port);
        ss = ssc.socket();
        ss.bind(address);

        System.out.println("Listening on " + ss); // Tell the world we're ready to go

        while (true) { // Keep accepting connections forever

            sc = ssc.accept(); // SocketChannel sc?

            System.out.println("Connection from " + sc); // Tell the world we've got it

            outputChannels.add(sc);
            //outputChannels.put(sc, null);

            new ServerThread(this, sc); // Create a new thread for this connection, and then forget about it
        }
    }

    ListIterator getOutputChannels() {
        //return outputChannels.elements();
        return outputChannels.listIterator(0);
    }

    void sendToAll(String message) {

        synchronized(sc) {

            for (ListIterator l = getOutputChannels(); l.hasNext();) { // for each client

                SocketChannel scBack = (SocketChannel) l.next(); // gets the output channel -- SocketChannel sc?

                try {
                    buffer.clear();
                    buffer = encoder.encode(CharBuffer.wrap(message));

                    scBack.write(buffer); // and sends the message
                } catch(IOException ie) { System.out.println(ie); }
            }
        }
    }

    void removeConnection(SocketChannel sc) {

        synchronized(outputChannels) { // synchronized so sendToAll() won't get messed up while it walks down the list of all output channels

            System.out.println("Removing connection to " + sc); // tells the world

            outputChannels.remove(sc); // removes it from our hashtable/list

            try {
                Socket s = sc.socket();
                s.close(); // makes sure it's closed
            } catch(IOException ie) {
                System.out.println("Error closing " + sc);
                ie.printStackTrace();
            }
        }
    }

    ServerSocket getServerSocket() {
        return ss;
    }

    static public void main(String args[]) throws Exception {
        try {
            final int port = Integer.parseInt(args[0]); // gets the port # from the command line

            Runnable serverRunnable = new Runnable() {
                public void run() {
                    try {
                        Server s = new Server( port ); // creates a Server object, which will automatically begin accepting connections
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            Thread serverThread = new Thread(serverRunnable);
            serverThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
--------------------------ServerThread.java------------------------------------
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;

public class ServerThread extends Thread {
    private Server server; // the server that spawned the thread
    private SocketChannel socketChannel; // the socket channel connected to the client
    private ByteBuffer buffer = ByteBuffer.allocate(50);
    private Charset charset = Charset.forName("US-ASCII");
    private CharsetDecoder decoder = charset.newDecoder();

    public ServerThread(Server server, SocketChannel socketChannel) {
        this.server = server; // saves the server parameter
        this.socketChannel = socketChannel; // saves the socket channel parameter

        start(); // starts up the thread
    }

    public void run() {

        try {
            while (true) {
                buffer.clear();
                int r = socketChannel.read(buffer);

                if (r == -1)
                    break;

                buffer.flip();

                CharBuffer charBuffer = decoder.decode(buffer);
                String message = charBuffer.toString();

                System.out.println("Sending " + message); // tells the world

                server.sendToAll(message); // and have the server send it to all clients
            }
        } catch(EOFException ie) {
        } catch(IOException ie) { // this doesn't need an error message

        ie.printStackTrace(); // this does; tells the world
        } finally {
            server.removeConnection( socketChannel ); // the connection is closed for one reason or another, so have the server deal with it
        }
    }
}
---------------------------Client.java--------------------------------
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import javax.swing.*;

public class Client extends Panel implements Runnable {

    private JLabel jl =  new JLabel();
    private TextArea ta = new TextArea(); // text area component for the visual display of the chat windows
    private TextField tf = new TextField(); // text field component for the visual display of the chat windows
    //private Socket s; // the socket connecting to the server
    private SocketChannel sc;
    private ByteBuffer buffer = ByteBuffer.allocate(50); // default capacity
    private Charset charset = Charset.forName("US-ASCII");
    private CharsetDecoder decoder = charset.newDecoder();
    private CharsetEncoder encoder = charset.newEncoder();

    public Client(String host, int port) {

        System.out.println("Testing... Client()"); // TEST

        setLayout(new BorderLayout()); // sets up the screen
        add("North", jl);
        add("Center", ta);
        add("South", tf);

        jl.setText(host);

        tf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                processMessage(e.getActionCommand()); // receives messages when someone types a line and hits return, using an anonymous class as a callback
            }
        } );

        try {
            InetSocketAddress address = new InetSocketAddress(InetAddress.getByName("localhost"), port);
            sc = SocketChannel.open();
            sc.configureBlocking(false);
            //Socket s = sc.socket();
            sc.connect(address);

            System.out.println("connected to " + sc); // gets a connection, tells the world

            new Thread(this).start(); // starts a background thread for receiving messages
        } catch(IOException ie) { System.out.println(ie); }
    }

    private void processMessage(String message) {
        try {
            buffer.clear();

            buffer = encoder.encode(CharBuffer.wrap(message));

            //buffer.flip();
            int numWritten = sc.write(buffer); // sends it to the server
            System.out.println("numWritten: " + numWritten); // TEST

            tf.setText(""); // clears out text input field
        } catch(IOException ie) { System.out.println(ie); }
    }

    public void run() {
        try {
            System.out.println("Testing... Client.run()"); // TEST

            while (true) {
                buffer.clear();

                /*
                try {
                    while (!sc.finishConnect()) // TEST
                        Thread.sleep(2000);
                } catch (InterruptedException ie) { System.out.println(ie); }
                */

                int r = sc.read(buffer); // <----------------------------------------------THIS GENERATES NotYetConnectedException

                if (r == -1)
                    break;

                buffer.flip();

                CharBuffer charBuffer = decoder.decode(buffer);
                String message = charBuffer.toString();
                System.out.println("received message: " + message); // TEST

                ta.append(message + "\n"); // prints it to our text window
            }
        } catch(IOException ie) { System.out.println(ie); }
    }

    static public void main(String args[]) throws Exception {
        try {
            final int port = Integer.parseInt(args[0]); // gets the port # from the command line

            Runnable clientRunnable = new Runnable() {
                public void run() {
                    try {
                        Client c = new Client("local host", port); // creates a Client object, which will automatically begin initiating connections
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            Thread clientThread = new Thread(clientRunnable);
            clientThread.start();

            JFrame win = new JFrame();
            win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            win.setSize(512, 512);
            win.setBackground(Color.gray);
            Container c = win.getContentPane();

            c.setLayout(new BorderLayout());
            c.add("Center", new Client("localhost", port));

            win.setVisible(true);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
---------------------------------------------------------------------------------
skyblue01Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
I'm not expert on nio, but I think the main problem is that if you want to use it non-blocking, you have to register the channel with a Selector to know when there's anything to read. There's an example at:

http://javaalmanac.com/egs/java.nio/NbClient.html?l=rel

but it's difficult finding full examples
0
CEHJCommented:
And look at

http://www.linux-mag.com/2002-11/java_03.html

particularly the text beginning

"For example, the following code creates a selector to monitor a socket channel called wire for inbound connections and reads:"
0
CEHJCommented:
And here's a whole chapter on selectors from a book on NIO:

http://www.oreilly.com/catalog/javanio/chapter/ch04.pdf
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

skyblue01Author Commented:
Yeah, I've read the tutorials on NIO and Asynchronous I/O.   But is it the blocking I/O that's causing the problem?   If you can compile and see what's the problem, that would help.
0
CEHJCommented:
>>But is it the blocking I/O that's causing the problem?

No - as i mentioned before, you have not registered the channel with a selector, which you should do if the channel is *non*-blocking
0
skyblue01Author Commented:
CEHJ, I solved the connection problem.   If you're still around, would you be able to take a look at the codes above (or maybe even run it) and tell me why the Client() constructor is called twice even if you only run the Clinet only once (after you run the Server)?   I'll grant the points instead for that since I'm not really understanding how they are run exactly and that could help the new problem I'm facing now.  
0
CEHJCommented:
The constructor is called once in the run method,

>>Client c = new Client("local host", port); // creates a Client object, which will automatically begin initiating connections

and once here:

>>c.add("Center", new Client("localhost", port));
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
skyblue01Author Commented:
How would I be able to reduce to just one call to the Client constructor while maintaining everything else the same?   Would it be wise to get rid of the latter one since I need the firtst one allows to make a connection faster?  
0
skyblue01Author Commented:
CEHJ, I got rid of the latter constructor and now I know exactly how the program is run.   I guess I forgot to get rid of that instantiation when I added the other one.   Thanks for pointing that out.  
0
CEHJCommented:
No problem ;-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.