[java] Blocking or non-blocking IO??

Started by
0 comments, last by VerMan 18 years, 10 months ago
Ok, here's the deal, I'm trying to finish the final project for my programming course (high school) and I'm planning on making a multi-connection chat server. I know this is generally an easy project, but I'm teaching myself the networking component of it completely by myself. I'm having trouble trying to wrap my Sockets (using blocking IO currently) in threads, but I'm trying to make my main thread wait for the monitor thread (it's what waits for a connection, plus, it makes a child thread for the IO handeling of each connection) to accept a connection. Currently I get an IOException because my program is opening another ServerSocket on the same port as the first, and it causes an IOException on the original one. After I connect (using telnet) I get an IllegalMonitorStateException error stating that "the thread is not the owner of the monitor you are trying to call wait() on". I'd liek to know if it'd be better to go with NIO or keep the blocking IO. Any example code or modifications would be GREATLY appreciated! Here's the broken code I have so far -.-

import java.io.*;
import java.net.*;
import java.util.*;

/**
BasicServer is the main class
for the server program, it
manages the child threads
that work with the connections
and it also does any other
things like file transfer if
required.
@author Blair Stacey
@version 1.1
 */
public class BasicServer
{
    private static int connectionCount;
    private static final int MAX_CONNECTIONS = 2;
    private static ArrayList connections = new ArrayList (3);

    public BasicServer ()
    {
        //connectionCount = 0;
        while (connections.size () < MAX_CONNECTIONS)
        {
            MonitorThread thisThread = new MonitorThread (this);
            connections.add (thisThread);
            try
            {
                synchronized (thisThread)
                {
                    thisThread.join ();
                    this.wait (); // Wait till woken by the connection after the client's connected.
                }
            }
            catch (InterruptedException e)
            {
                System.out.println ("ERROR: Main Thread Interrupted!");
            }
            catch (IllegalStateException e)
            {
            }
            catch (IllegalMonitorStateException e)
            {
            }
        }
    }


    public void postMSG (String MSG)
    {
        for (int i = 0 ; i < connectionCount ; i++)
        {
            MonitorThread thisConnection = (MonitorThread) connections.get (i);
            thisConnection.post (MSG);
        }
    }


    public static void main (String[] args)
    {
        BasicServer instance = new BasicServer ();
    }
}

/**
MonitorThread implements Runnable interface to
make a child thread capable of working with the IO
parts of network communication andcommunication
between clients.
@author Blair Stacey
@version 1.0
 */
class MonitorThread extends Thread
{
    private ServerSocket connection;
    private BasicServer s;
    private ConnectionThread client;

    MonitorThread (BasicServer svr)
    {
        s = svr;
        Thread t = new Thread (this);
        t.start ();
    }


    public void run ()
    {
        setPriority (Thread.MIN_PRIORITY);
        Socket incoming;

        try
        {
            connection = new ServerSocket (1337); // Listen for connection
            incoming = connection.accept ();      // Accept connection

            PrintWriter output = new PrintWriter (incoming.getOutputStream (), true);  // Autoflushing PrintWriter for text output
            BufferedReader input = new BufferedReader (new InputStreamReader (incoming.getInputStream ()));  // BufferedReader for text input
            client = new ConnectionThread (output, input, incoming, s); // Delegate information to a connection child thread
            synchronized (s) {notify (); // Wake main hread that's waiting to open another connection.
            client.join ();
            }
        }
        catch (IOException e)
        {
            System.out.println ("ERROR: Connection Failed!");
        }
        catch (InterruptedException e)
        {
            System.out.println ("ERROR: Monitor Thread Interrupted!");
        }
    }


    public void post (String MSG)
    {
        client.post (MSG);
    }
}

/**
ConnectionThread implements Runnable interface to
become a child thread capable of working with the
IO parts of network communication andcommunication
between clients.
@author Blair Stacey
@param PrintWriter out, BufferedReader in, Socket client
@version 1.0
 */
class ConnectionThread extends Thread
{
    private BasicServer s;
    private String clientText = new String ();
    private PrintWriter output;
    private BufferedReader input;
    private Socket clientConnection;
    private final int IS_MESSAGE = 1;
    private final int IS_COMMAND = 2;

    ConnectionThread (PrintWriter out, BufferedReader in, Socket client, BasicServer svr)
    {
        s = svr;
        Thread t = new Thread (this);
        output = out;
        input = in;
        clientConnection = client;
        t.start ();
    }


    public void run ()
    {
        try
        {
            while ((clientText = input.readLine ()) != null)
            {
                int flags = 0;
                switch (flags | (int) clientText.charAt (0))
                {
                    case IS_MESSAGE:
                        s.postMSG (clientText.substring (1, (clientText.length () - 1)));
                        break;
                    case IS_COMMAND:
                        break;
                    default:
                        s.postMSG (clientText.substring (0, clientText.length ()));
                        break;
                }
            }
        }
        catch (IOException e)
        {
            System.out.println ("Disconnected...");
        }
    }


    public void post (String MSG)
    {
        System.out.println ("Printing: \"" + MSG + "\"");
        output.print (MSG);
        output.flush ();
    }
}
Advertisement
maybe this will help you:
http://java.sun.com/j2se/1.4.2/docs/api/java/net/MulticastSocket.html

I used Multicast Sockets to implement a chat a couple of years ago...

This topic is closed to new replies.

Advertisement