Having problems with my Java chat program code

Started by
0 comments, last by bob_the_third 21 years, 6 months ago
I'm working on a peer-to-peer chat program in Java for fun (okay I'll be completely honest...the program that I am currently writing IS for fun, but I'm writing it as part of the software development process for my senior design project making it almost sort of technically speaking *cough* homework. However I'm not asking anyone to tell me how to write the program, I don't even WANT anyone to tell me that because I enjoy the challenge of making things work, but I'm stuck on a technical detail of Java.). So the problem I'm having is with multi-threading. The program has two threads. One thread listens for data and the other thread sends data. The app is in console mode, so I use System.out as my output stream and System.in as my input stream. When I run two instances of the program on my system with the following command line arguments: "p2pchat localhost 3000 4000" and "p2pchat localhost 4000 3000", they establish a two-way connection like they are supposed to, they both take user input and write it to the socket as desired, but the listener threads seem to be dead. I've posted the source below:
      
//This is a TCP peer-to-peer text chat program.

//Usage:  java p2pchat address receiveport sendport


//KNOWN BUGS:

//I can't seem to get both the server and the client threads to share the CPU


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

//This class waits for a connection from another chat client and then listens

//to whatever the client has to say:

class ChatServer extends Thread {
    private Socket connectionSocket = null;
    private int port;
    private String address;
    private FileWriter logFile = null;

    public ChatServer( String address, int port /*, String fileName*/ )
    {
        this.port = port;
        this.address = address;
        //setDaemon(true);
        /*try{ logFile = new FileWriter( fileName ); } catch( Exception e ) { System.out.println( e ); };*/
        start();
    }

    public void run()
    {

        String clientData = "";

        // Create welcome socket for the client to connect to us.
        ServerSocket welcomeSocket = null;

        try{
        welcomeSocket = new ServerSocket(port);

        System.out.println( "Available for connections." );
        System.out.println( "SOCKET INFO" );
        System.out.println( "====================================" );
        System.out.println( welcomeSocket );
        System.out.println( "====================================" );
        } catch( Exception e ) {
                System.out.println( e );
        }

        while(true) {
            try
            {
            // Create a socket when there is a knock at the door
            connectionSocket = welcomeSocket.accept();
            System.out.println( "Connection established." );
            System.out.println( connectionSocket );

            BufferedReader inFromClient = new BufferedReader
            (new InputStreamReader(connectionSocket.getInputStream()));
            
            //Talk to this client as long as they want:
            do
            {
                 System.out.println( "WAITING FOR MESSAGE FROM REMOTE HOST..." );
                 System.out.flush();
                 // Read info from socket
                 clientData = inFromClient.readLine();
                 System.out.println( ">>> " + clientData );
                 yield();
             }  while( !clientData.equals( "QUIT/" ) );

             System.out.println( "Connection closed." );
             }  catch( Exception e ) {
                  System.out.println( e );
             }
       }
    }
};



//This class does all the talking:
class ChatClient extends Thread {
    private int port;
    private String address;
    private String myData = null;

    public ChatClient( String address, int port )
    {
        this.port = port;
        this.address = address;
        //setDaemon(true);
        start();
    }

    public void run()
    {
        // Create socket to hostname or IP address and port #
        // Initiates TCP connection between client and server
        Socket clientSocket = null;
        DataOutputStream outToClient = null;

        BufferedReader inFromUser =
        new BufferedReader(new InputStreamReader(System.in));


        System.out.println( "Connecting to remote host..." );

        while(true)
        {
                try{
                //Keep trying to connect if we haven't yet.
                if( clientSocket == null )
                {
                        clientSocket = new Socket(address, port);
                        outToClient = new DataOutputStream(clientSocket.getOutputStream());
                }


                if ( clientSocket!=null )
                {
                        System.out.print( ": " );
                        myData = inFromUser.readLine();
                        outToClient.writeBytes( myData );
                        outToClient.flush();
                        System.out.println( "MESSAGE SENT TO REMOTE HOST." );
                }
                } catch( Exception e ) {
                        System.out.println( e );
                }
         }
    }
};




class p2pchat {
    public static void main(String args[]) throws Exception {
        String clientSentence;
        String capitalizedSentence;
        int receiveport = Integer.parseInt(args[1]);
        int sendport = Integer.parseInt(args[2]);
        //String logFileName = args[3];
        String address = args[0];

        ChatServer serve = new ChatServer(address, receiveport /*, logFileName*/ );
        ChatClient client = new ChatClient(address, sendport);
    }
}
      
[edited by - bob_the_third on October 3, 2002 11:55:29 PM] [edited by - bob_the_third on October 3, 2002 11:56:02 PM]
Advertisement
My guess is that program flow goes into the while(true) section of the server class and never comes out. Don''t you need to sleep somewhere in Threads to give time to other threads?
Pepper in a whole lot more System.err.println()''s and I''m sure you will figure it out...

This topic is closed to new replies.

Advertisement