Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 17 of 17

Thread: JAVA NETWORK client/server architechture

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default JAVA NETWORK client/server architechture

    ok. so this is the Server and client code snippet. please can someone else run it and tell me why my code is giving this much trouble. am using a windows 7 64-bit system on a jdk 7U40 installer. my firewall is turned off from both windows and my antivirus program.
    below is the code;

    Server class
    // Fig. 27.5: Server.java
    // Server portion of a client/server stream-socket connection. 
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
     
    public class Server extends JFrame 
    {
       private JTextField enterField; // inputs message from user
       private JTextArea displayArea; // display information to user
       private ObjectOutputStream output; // output stream to client
       private ObjectInputStream input; // input stream from client
       private ServerSocket server; // server socket
       private Socket connection; // connection to client
       private int counter = 1; // counter of number of connections
     
       // set up GUI
       public Server()
       {
          super( "Server" );
     
          enterField = new JTextField(); // create enterField
          enterField.setEditable( false );
          enterField.addActionListener(
             new ActionListener() 
             {
                // send message to client
                public void actionPerformed( ActionEvent event )
                {
                   sendData( event.getActionCommand() );
                   enterField.setText( "" );
                } // end method actionPerformed
             } // end anonymous inner class
          ); // end call to addActionListener
     
          add( enterField, BorderLayout.NORTH );
     
          displayArea = new JTextArea(); // create displayArea
          add( new JScrollPane( displayArea ), BorderLayout.CENTER );
     
          setSize( 300, 150 ); // set size of window
          setVisible( true ); // show window
       } // end Server constructor
     
       // set up and run server 
       public void runServer()
       {
          try // set up server to receive connections; process connections
          {
             server = new ServerSocket(12345,100); // create ServerSocket
     
             while ( true ) 
             {
                try 
                {
                   waitForConnection(); // wait for a connection
                   getStreams(); // get input & output streams
                   processConnection(); // process connection
                } // end try
                catch ( EOFException eofException ) 
                {
                   displayMessage( "\nServer terminated connection" );
                } // end catch
                finally 
                {
                   closeConnection(); //  close connection
                   ++counter;
                } // end finally
             } // end while
          } // end try
          catch ( IOException ioException ) 
          {
             ioException.printStackTrace();
          } // end catch
       } // end method runServer
     
       // wait for connection to arrive, then display connection info
       private void waitForConnection() throws IOException
       {
          displayMessage( "Waiting for connection\n" );
          connection = server.accept(); // allow server to accept connection            
          displayMessage( "Connection " + counter + " received from: " +
             connection.getInetAddress().getHostName() );
       } // end method waitForConnection
     
       // get streams to send and receive data
       private void getStreams() throws IOException
       {
          // set up output stream for objects
          output = new ObjectOutputStream( connection.getOutputStream() );
          output.flush(); // flush output buffer to send header information
     
          // set up input stream for objects
          input = new ObjectInputStream( connection.getInputStream() );
     
          displayMessage( "\nGot I/O streams\n" );
       } // end method getStreams
     
       // process connection with client
       private void processConnection() throws IOException
       {
          String message = "Connection successful";
          sendData( message ); // send connection successful message
     
          // enable enterField so server user can send messages
          setTextFieldEditable( true );
     
          do // process messages sent from client
          { 
             try // read message and display it
             {
                message = ( String ) input.readObject(); // read new message
                displayMessage( "\n" + message ); // display message
             } // end try
             catch ( ClassNotFoundException classNotFoundException ) 
             {
                displayMessage( "\nUnknown object type received" );
             } // end catch
     
          } while ( !message.equals( "CLIENT>>> TERMINATE" ) );
       } // end method processConnection
     
       // close streams and socket
       private void closeConnection() 
       {
          displayMessage( "\nTerminating connection\n" );
          setTextFieldEditable( false ); // disable enterField
     
          try 
          {
             output.close(); // close output stream
             input.close(); // close input stream
             connection.close(); // close socket
          } // end try
          catch ( IOException ioException ) 
          {
             ioException.printStackTrace();
          } // end catch
       } // end method closeConnection
     
       // send message to client
       private void sendData( String message )
       {
          try // send object to client
          {
             output.writeObject( "SERVER>>> " + message );
             output.flush(); // flush output to client
             displayMessage( "\nSERVER>>> " + message );
          } // end try
          catch ( IOException ioException ) 
          {
             displayArea.append( "\nError writing object" );
          } // end catch
       } // end method sendData
     
       // manipulates displayArea in the event-dispatch thread
       private void displayMessage( final String messageToDisplay )
       {
          SwingUtilities.invokeLater(
             new Runnable() 
             {
                public void run() // updates displayArea
                {
                   displayArea.append( messageToDisplay ); // append message
                } // end method run
             } // end anonymous inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method displayMessage
     
       // manipulates enterField in the event-dispatch thread
       private void setTextFieldEditable( final boolean editable )
       {
          SwingUtilities.invokeLater(
             new Runnable()
             {
                public void run() // sets enterField's editability
                {
                   enterField.setEditable( editable );
                } // end method run
             }  // end inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method setTextFieldEditable
    } // end class Server
     
    Client class
    // Fig. 27.7: Client.java
    // Client portion of a stream-socket connection between client and server.
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
     
    public class Client extends JFrame 
    {
       private JTextField enterField; // enters information from user
       private JTextArea displayArea; // display information to user
       private ObjectOutputStream output; // output stream to server
       private ObjectInputStream input; // input stream from server
       private String message = ""; // message from server
       private String chatServer; // host server for this application
       private Socket client; // socket to communicate with server
     
       // initialize chatServer and set up GUI
       public Client( String host )
       {
          super( "Client" );
     
          chatServer = host; // set server to which this client connects
     
          enterField = new JTextField(); // create enterField
          enterField.setEditable( false );
          enterField.addActionListener(
             new ActionListener() 
             {
                // send message to server
                public void actionPerformed( ActionEvent event )
                {
                   sendData( event.getActionCommand() );
                   enterField.setText( "" );
                } // end method actionPerformed
             } // end anonymous inner class
          ); // end call to addActionListener
     
          add( enterField, BorderLayout.NORTH );
     
          displayArea = new JTextArea(); // create displayArea
          add( new JScrollPane( displayArea ), BorderLayout.CENTER );
     
          setSize( 300, 150 ); // set size of window
          setVisible( true ); // show window
       } // end Client constructor
     
       // connect to server and process messages from server
       public void runClient() 
       {
          try // connect to server, get streams, process connection
          {
             connectToServer(); // create a Socket to make connection
             getStreams(); // get the input and output streams
             processConnection(); // process connection
          } // end try
          catch ( EOFException eofException ) 
          {
             displayMessage( "\nClient terminated connection" );
          } // end catch
          catch ( IOException ioException ) 
          {
             ioException.printStackTrace();
          } // end catch
          finally 
          {
             closeConnection(); // close connection
          } // end finally
       } // end method runClient
     
       // connect to server
       private void connectToServer() throws IOException
       {      
          displayMessage( "Attempting connection\n" );
     
          // create Socket to make connection to server
          client = new Socket( InetAddress.getByName( chatServer ),12345);
     
          // display connection information
          displayMessage( "Connected to: " + 
             client.getInetAddress().getHostName() );
       } // end method connectToServer
     
       // get streams to send and receive data
       private void getStreams() throws IOException
       {
          // set up output stream for objects
          output = new ObjectOutputStream( client.getOutputStream() );      
          output.flush(); // flush output buffer to send header information
     
          // set up input stream for objects
          input = new ObjectInputStream( client.getInputStream() );
     
          displayMessage( "\nGot I/O streams\n" );
       } // end method getStreams
     
       // process connection with server
       private void processConnection() throws IOException
       {
          // enable enterField so client user can send messages
          setTextFieldEditable( true );
     
          do // process messages sent from server
          { 
             try // read message and display it
             {
                message = ( String ) input.readObject(); // read new message
                displayMessage( "\n" + message ); // display message
             } // end try
             catch ( ClassNotFoundException classNotFoundException ) 
             {
                displayMessage( "\nUnknown object type received" );
             } // end catch
     
          } while ( !message.equals( "SERVER>>> TERMINATE" ) );
       } // end method processConnection
     
       // close streams and socket
       private void closeConnection() 
       {
          displayMessage( "\nClosing connection" );
          setTextFieldEditable( false ); // disable enterField
     
          try 
          {
             output.close(); // close output stream
             input.close(); // close input stream
             client.close(); // close socket
          } // end try
          catch ( IOException ioException ) 
          {
             ioException.printStackTrace();
          } // end catch
       } // end method closeConnection
     
       // send message to server
       private void sendData( String message )
       {
          try // send object to server
          {
             output.writeObject( "CLIENT>>> " + message );
             output.flush(); // flush data to output
             displayMessage( "\nCLIENT>>> " + message );
          } // end try
          catch ( IOException ioException )
          {
             displayArea.append( "\nError writing object" );
          } // end catch
       } // end method sendData
     
       // manipulates displayArea in the event-dispatch thread
       private void displayMessage( final String messageToDisplay )
       {
          SwingUtilities.invokeLater(
             new Runnable()
             {
                public void run() // updates displayArea
                {
                   displayArea.append( messageToDisplay );
                } // end method run
             }  // end anonymous inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method displayMessage
     
       // manipulates enterField in the event-dispatch thread
       private void setTextFieldEditable( final boolean editable )
       {
          SwingUtilities.invokeLater(
             new Runnable() 
             {
                public void run() // sets enterField's editability
                {
                   enterField.setEditable( editable );
                } // end method run
             } // end anonymous inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method setTextFieldEditable
    } // end class Client
    Last edited by moonah; October 5th, 2013 at 01:09 AM. Reason: to put the proper code tags


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: JAVA NETWORK client/server architechture

    Please edit your post and wrap your code with code tags:
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.

    my code is giving this much trouble
    Please explain. Copy the full contents of the console and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    Please I have done as you suggested, hope you can help with the problem now?
    Cheers.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: JAVA NETWORK client/server architechture

    why my code is giving this much trouble
    Please explain what the problem is. What happens when you execute the code?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    It thorws a can not connect error. Av tried everything to resolve it from disabling all firewares to installin a 32-bit installer on a 32bit system. To contacting paul deitel, who also suggested this, since its his code. But it keeps throwing the same erro and there's no syntax or logic error from anywhere. If myclient can't connect to a server on my system then...

  6. #6
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: JAVA NETWORK client/server architechture

    your not telling the server what its host IP is.. the port is set to 12345 which is sort of dramatic but should be fine for an example run / learning developer. However you will need to set the IP of the host also.

    The server needs to know the IP that it is hosting look at this guide
    ServerSocket (Java Platform SE 7 b123)

    so
    ServerSocket servSocket = new ServerSocket(12345, 100, "127.0.0.1");
    -------

    or specify the ip elsewhere however you should use localhost so it will allow the client to connect to the server. wan ip wont work unless you port forward which is another topic all together.

    The client should then be set to connect to 127.0.0.1 (IP) and 12345 (PORT) which then should connect with no drama.
    Last edited by macko; October 8th, 2013 at 06:04 AM. Reason: fix mistake with ip string

  7. #7
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    Quote Originally Posted by macko View Post
    your not telling the server what its host IP is.. the port is set to 12345 which is sort of dramatic but should be fine for an example run / learning developer. However you will need to set the IP of the host also.

    The server needs to know the IP that it is hosting look at this guide
    ServerSocket (Java Platform SE 7 b123)

    so
    ServerSocket servSocket = new ServerSocket(12345, 100, "127.0.0.1");
    -------

    or specify the ip elsewhere however you should use localhost so it will allow the client to connect to the server. wan ip wont work unless you port forward which is another topic all together.

    The client should then be set to connect to 127.0.0.1 (IP) and 12345 (PORT) which then should connect with no drama.
    Macko unfortunately I tried out what you suggested. But the complier doesn't recognise a ocnstructor for the above object.. Pleae try it out asawell your self .

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: JAVA NETWORK client/server architechture

    have you tried the server on another OS like WinXP to see if there is a problem with Win7?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    Macko I tried it on vista and it keeps giving me the same can not connect error. Keeping in mind that the genesis of this whole problem came from the can not connect to server error. Could you also give it a trial run on ur OS and see if it would work and if it does, give me your OS specs. Am thinking its a java 7/ windows 7 issue.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: JAVA NETWORK client/server architechture

    Have you tried putting the server on WinXP?
    I have my own HTTP server I use for testing. It is accessible when run on XP but not on Win7.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    I will definitely have to give it a try then. I will partition my system and install an XP on a virtual machine.

  12. #12
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    Thanks norm. the fault has been from me all along. instead of me to run two different instances of the command prompt window and run the server application first, i kept running them individually. the application runs without any hassles now. thanks guys for all the assistance.

  13. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: JAVA NETWORK client/server architechture

    Can you explain where, how and in what order each program is being executed?
    If you don't understand my answer, don't ignore it, ask a question.

  14. #14
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    The server executed first before the client. where, on the local host from command line instance.

  15. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: JAVA NETWORK client/server architechture

    Then both programs were executed on the same PC which was using Win7.
    Were the server and the client classes executed with their own JVM
    or were they both executed in the same JVM from a third class that called their main() methods, server first and then client?
    If you don't understand my answer, don't ignore it, ask a question.

  16. #16
    Junior Member
    Join Date
    Jan 2012
    Posts
    15
    My Mood
    Nerdy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JAVA NETWORK client/server architechture

    they were both executed from the same PC using windows7 from different instance of the command prompt window. so its like...
    ServerTest.java first, then Client Test .java. but the server test has to run first so it won't throw the connection exception.

  17. #17
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: JAVA NETWORK client/server architechture

    Ok. Thanks. I usually use a main() like this for testing client/server code in a single JVM:
       public static void main(String[] args) {
          Thread t1 = new Thread(new Runnable() {
             public void run() {
                try{new Server().runServer();}catch(Exception x){x.printStackTrace();}
             }
          });
          t1.start();
     
          try{Thread.sleep(100);}catch(Exception x){}  //  Let server start
     
          Thread t2 = new Thread(new Runnable() {
             public void run() {
                try{new Client("127.0.0.1").runClient();}catch(Exception x){x.printStackTrace();}
             }
          });
          t2.start();
     
     
          // wait and exit
          //  In case there is a infinite loop/bug that traps the GUI
          try{Thread.sleep(15000);}catch(Exception x){}
          System.out.println("Exiting main");
          System.exit(0);
     
       }
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. my encrypting simple client to server program unable to get the key from client
    By Paytheprice in forum What's Wrong With My Code?
    Replies: 11
    Last Post: February 3rd, 2013, 07:15 AM
  2. Replies: 0
    Last Post: May 31st, 2012, 05:35 PM
  3. network: 2 client - 1 server
    By Askan in forum Java Networking
    Replies: 0
    Last Post: March 31st, 2012, 09:02 AM
  4. TCP/IP java client, c++ server
    By akboyd88 in forum Java Networking
    Replies: 0
    Last Post: March 24th, 2011, 10:46 AM
  5. [Java] Client - server, example
    By Grabar in forum Java Networking
    Replies: 6
    Last Post: January 22nd, 2011, 01:56 PM