Solved

global chat server program design

Posted on 2003-11-07
10
920 Views
Last Modified: 2008-01-16
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();
        }
    }
}
---------------------------------------------------------------------------------
0
Comment
Question by:skyblue01
  • 6
  • 4
10 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9706721
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 9706728
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 9706739
And here's a whole chapter on selectors from a book on NIO:

http://www.oreilly.com/catalog/javanio/chapter/ch04.pdf
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:skyblue01
ID: 9706988
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 9707026
>>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
 

Author Comment

by:skyblue01
ID: 9707233
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
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
ID: 9707350
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
 

Author Comment

by:skyblue01
ID: 9707408
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
 

Author Comment

by:skyblue01
ID: 9707495
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 9707531
No problem ;-)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question