| | |
Networked chat application between two clients
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
I'm trying to create a client/server setup that allows two clients to communicate with each other. The problem is that when I run the application the the message does not go to the send client, only to the server. Here is the source code.
Class MorseServer
Main method
Class MorseServer
java Syntax (Toggle Plain Text)
import javax.swing.JTextArea; import javax.swing.JFrame; import javax.swing.JScrollPane; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import javax.swing.SwingUtilities; public class MorseServer extends JFrame { private JTextArea serverDisplay; private ServerSocket server; // server socket to connect with users private ExecutorService messageExchange; private Lock messageLock; private Condition userTwoConnect; private Client[] client; private boolean twoUserConnected = false; private static String messageBuffer; public MorseServer() { super("Morse Code Server"); serverDisplay = new JTextArea( "Waiting for connection\n" ); serverDisplay.setEditable( false ); add( new JScrollPane( serverDisplay ) ); messageExchange = Executors.newFixedThreadPool(2); messageLock = new ReentrantLock(); userTwoConnect = messageLock.newCondition(); client = new Client[ 2 ]; } public void execute() { try { server = new ServerSocket( 22222, 2 ); } catch( IOException ioException ) { ioException.printStackTrace(); System.exit(1); } waitForConnection(); messageExchange.execute( client[0] ); messageExchange.execute( client[1] ); messageLock.lock(); try { client[ 0 ].setSuspended(false); userTwoConnect.signal(); } finally { messageLock.unlock(); } } public void waitForConnection() { messageBuffer = new String(); for( int i = 0; i < client.length; i++ ) { try { client[ i ] = new Client( server.accept(), i, messageBuffer ); // waits for connection messageExchange.execute( client[ i ] ); } catch( IOException ioException ) { ioException.printStackTrace(); System.exit(1); } // end catch }// end for twoUserConnected = true; } private void displayInformation( final String info ) { SwingUtilities.invokeLater( new Runnable() { public void run() { serverDisplay.append( "\n" + info ); } } ); } private class Client implements Runnable { private Socket connection; private int userNumber; private ObjectInputStream input; private ObjectOutputStream output; private boolean suspended = true; private String message; //private Condition canRead; //private Condition canWrite; public Client( Socket socket, int number, String msg ) { connection = socket; userNumber = number; messageBuffer = msg; //canRead = messageLock.newCondition(); //canWrite = messageLock.newCondition(); try { input = new ObjectInputStream( connection.getInputStream() ); output = new ObjectOutputStream( connection.getOutputStream() ); } catch( IOException ioException ) { ioException.printStackTrace(); System.exit(1); } } public void run() { try { displayInformation( "User Number: " + userNumber + " connected\n" ); output.writeObject( "Connection sucessful!\n" ); output.flush(); if( !twoUserConnected ) { if( userNumber == 0 ) { output.writeObject( "Waiting for correspondent\n" ); output.flush(); messageLock.lock(); // wating for second client try { while( suspended ) { userTwoConnect.await(); } } catch( InterruptedException exception ) { exception.printStackTrace(); } finally { messageLock.unlock(); } output.writeObject( "Second user connected!\n"); output.flush(); } else { output.writeObject( "Connection sucessful!\n" ); output.flush(); } } String msg; while( true ) { if ( input.equals(null) ) { continue; } else { messageBuffer = ( String ) input.readObject(); msg = messageBuffer; displayInformation( messageBuffer ); //while ( !userTerminate( message ) ) //{ //messageLock.lock(); output.writeObject ( messageBuffer ); output.flush(); Thread.sleep(10000); } } } catch( ClassNotFoundException exception ) { exception.printStackTrace(); } catch( IOException ioException ) { ioException.printStackTrace(); } catch( InterruptedException exception ) { exception.printStackTrace(); } finally { try { messageLock.unlock(); connection.close(); } catch( IOException ioException ) { ioException.printStackTrace(); System.exit(1); }// end catch } // end finally } // end method run private boolean userTerminate( String msg ) { if ( msg.equals( "User>>> TERMINATE" ) ) return true; else return false; } public void setSuspended( boolean state ) { suspended = state; } } }
Main method
java Syntax (Toggle Plain Text)
import javax.swing.JFrame; public class MorseServerTest { public static void main( String args[] ) { MorseServer application = new MorseServer(); application.setSize(300,300); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); application.setResizable(false); application.setVisible(true); application.execute(); } }
If you don't get any reply after about 5 days, you probably won't get any afterwards. Check out this.
"You know you're a computer geek when you try to shoo a fly away from the monitor screen with your cursor. That just happened to me. It was scary." - Juuso Heimonen.
"The only truly secure computer is one buried in concrete, with the power turned off and the network cable cut." - Anonymous.
"The only truly secure computer is one buried in concrete, with the power turned off and the network cable cut." - Anonymous.
![]() |
Other Threads in the Java Forum
- Previous Thread: why some classes are not serializable
- Next Thread: Any good Regex tutorials or books?
| Thread Tools | Search this Thread |
Tag cloud for Java
actionlistener android api apple applet application apps arguments array arrays automation balls binary bluetooth card chat class classes clear client code component consumer database draw eclipse ee error event exception fractal free game gameprogramming gis givemetehcodez graphics gui html ide image input integer j2me j2seprojects java javaprojects jni jpanel julia jvm key linux list loop machine map method methods migrate mobile mobiledevelopmentcreatejar myaggfun netbeans newbie nextline nls notdisplaying number oracle output print problem program programming project recursion recursive scanner screen security server set size sms socket sort spamblocker sql sqlite string sun swing terminal test threads time tree trolltech windows





