11 Replies Latest reply on Sep 1, 2008 12:54 AM by 807589

    client server application

    807589
      hello everyone. i am new in java programming and i want to write a p2p simulation program.
      here is my server code and my client code
      import java.io.*;
      import java.net.*;
      import java.util.*;

      public class Client1
      {
           private Socket clientSocket ;
           private PrintWriter out ;
           private BufferedReader in ;
           //private BufferedReader stdIn ;SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
           private Scanner stdIn;
           private InetAddress host;
           private String fromServer;
           private String toServer;
           private String clientName="Billy";


      public void runClient() throws IOException
      {

                host = InetAddress.getLocalHost();

                try
                {
           System.out.println("Attempting to connect...");
      clientSocket = new Socket(host.getHostName(), 12345);
      System.out.println("Connected");
      out = new PrintWriter(clientSocket.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      //stdIn= new BufferedReader(new InputStreamReader(System.in)); SSSSSSSSSSSSSSSSSS
      System.out.println("Got I/O Streams");
      }
                catch (UnknownHostException e)
      {
      System.err.println("Don't know about host");
      System.exit(1);
      }
      catch (IOException e)
      {
      System.err.println("Couldn't get I/O for the connection to: Billy.");
      System.exit(1);
      }




      out.println(clientName);

      fromServer=in.readLine();


           
           System.out.println(fromServer);
           
           stdIn = new Scanner(System.in);
           toServer=stdIn.nextLine(); // epilogi "m" or "n"



      while((!toServer.equalsIgnoreCase("m")) && (!toServer.equalsIgnoreCase("c")) ) // apofigi lathos input
      {
           System.out.println("You must type m or c");
           //toServer=stdIn.readLine(); SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
      }
      out.println(toServer);



      if( toServer.equalsIgnoreCase("m")) // an dialiksei o xristis manual
      {
                for (int i=0;i<=2;i++)
                {
                fromServer=in.readLine();
                //while ( (fromServer=in.readLine()) != null )
                System.out.println(fromServer);
                }
                manualConfig();
                     
      }
           
      else if ( toServer.equalsIgnoreCase("c"))
      {
                
      }

      out.println("testin null");










      out.close();
           in.close();
           clientSocket.close();
      }

      private void manualConfig()
      {
           Scanner input = new Scanner(System.in);
           
           
           while ( !(input.nextLine().equalsIgnoreCase("ok")) )
           {
                
                toServer=input.nextLine();
                out.println(toServer);
           }
           
           
           
      }

      }

      SERVER CODE

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

      public class MyServer

      {
           private ServerSocket server;
           private Socket connection;
           private String fromClient;
           private String toClient;
           private PrintWriter out;
           private BufferedReader in;
           private String clientName;
           private Formatter toFile;
           
           public void runServer()
           {
                try
                {
                     server=new ServerSocket(12345);
                     
                     try
                     {
                          waitForConnection();
                          getStreams();
                          processConnection();
                     }
                     catch (EOFException e)
                     {
                          System.out.println("Server terminated connection");
                     }
                     finally
                     {
                          closeConnection();
                     }     
                }//end of try
                catch (IOException e)
      {
      System.err.println("Could not listen on port: 12345.");
      System.exit(1);
      }
           }//End of runServer
           
           
           private void waitForConnection() throws IOException
           {
                System.out.println("Waiting for connection");
                
                try
                {
                     connection = server.accept();
                     System.out.println("Connected");
                }
                
                catch (IOException e)
      {
      System.err.println("Problem closing connections");
      System.exit(1);
      }
                
           }//End waitForConnection
           
           private void getStreams() throws IOException
           {
                out = new PrintWriter(connection.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                System.out.println("Got I/O streams");
                
           } //End of getStreams
           
           private void processConnection() throws IOException
           {
                
                clientName=in.readLine();
                
                
                out.println("Do you want to insert your shared files(M)anually or by (C)onfuguration file?");
                
                fromClient=in.readLine();
                
                
                if(fromClient.equalsIgnoreCase("m"))
                {
                     out.println("You chose Manually");
                     manualConfig();
                }          
                else
                     out.println("You chose Configuration file");
                     
                fromClient = in.readLine();
                     System.out.println(fromClient);
                
           }//End of processConnection
           
           private void closeConnection() throws IOException
           {
                in.close();
                out.close();
                connection.close();
           }
           
           private void manualConfig() throws IOException
           {
                String fileName = clientName+".txt";
                File file = new File(fileName);
                
                out.println("Doste onoma, eidos (mp3,txt...), keyword kai megethos arxeioy(bytes)");
                out.println("Otan teleiwsete patiste ok");

                try
                {
                     
                     toFile = new Formatter(fileName);
      *               while( !((fromClient = in.readLine()).equalsIgnoreCase("ok") ) )*
      *               {*
      *               System.out.println(fromClient);*
      *               toFile.format(" %s\n" ,fromClient);*
                }
                
                
                
                }
                catch (SecurityException e)
                {
                     System.err.println("You do not have write access");
                     System.exit(1);
                }
                catch (FileNotFoundException e)
                {
                     System.err.println("Error creating file");
                     System.exit(1);
                }
                
                finally
                {
                     toFile.close();
                }
                
                
                     
                
           }
           
           
      }



      the thing is that after my program returns from the server method manual config it writes into the file that it creates the testing null String whwn i would expect it not to
      Can someone tell me why this is so?
      also when i try the loop starting with while ( (fromclient=in.readLine() ) != null ) the program does not respond. it must have to do sthing with the inputstram.


      can someone explian to me how the setrver client programs switch turns?

      for ex if i want to sent some strings to client and dont know haow many if i try to print these lines to screen with the loop ( (fromclient=in.readLine() ) != null ) the programm stops.
      thanx!!!

      Edited by: Billy79 on Aug 31, 2008 2:29 PM
        • 1. Re: client server application
          800351
          Post a compilable and runnable code.

          Use CODE tags for proper formatting of the code.
          Don't write like this:
          for (......) // comment comment {
          while (.....) // comment comment {
          They won't compile.
          • 2. Re: client server application
            darrylburke
            {color:red}{size:20px}CROSS POSTED{size}{color}
            [http://forums.sun.com/thread.jspa?threadID=5327777]

            Cross posting is rude.

            db
            • 3. Re: client server application
              807589
              You are right, after i posted my question hre i saw the network topic.
              As i am new at this if you can tell me how to withdraw my question from this topic so as to leave it only on the networking forum i would be obliged.

              no intention to be rude just looking for answers to my problem
              • 4. Re: client server application
                800351
                Your Client1.manualConfig() method was written wrong. Try this code:
                import java.io.*;
                import java.net.*;
                import java.util.*;
                
                public class MyServer{
                  private ServerSocket server;
                  private Socket connection;
                  private String fromClient;
                  private String toClient;
                  private PrintWriter out;
                  private BufferedReader in;
                  private String clientName;
                  private Formatter toFile;
                
                  public void runServer(){
                    try{
                      server=new ServerSocket(12345);
                
                      try{
                        waitForConnection();
                        getStreams();
                        processConnection();
                      }
                      catch (EOFException e){
                        System.out.println("Server terminated connection");
                      }
                      finally{
                        closeConnection();
                      }
                    }
                    catch (IOException e){
                      System.err.println("Could not listen on port: 12345.");
                      System.exit(1);
                    }
                  }
                
                  private void waitForConnection() throws IOException{
                    System.out.println("Waiting for connection");
                    try{
                      connection = server.accept();
                      System.out.println("Connected");
                    }
                    catch (IOException e){
                      System.err.println("Problem closing connections");
                      System.exit(1);
                    }
                  }
                
                  private void getStreams() throws IOException{
                    out = new PrintWriter(connection.getOutputStream(), true);
                    in = new BufferedReader
                      (new InputStreamReader(connection.getInputStream()));
                    System.out.println("Got I/O streams");
                  }
                
                  private void processConnection() throws IOException{
                    clientName = in.readLine();
                System.out.println("got client name " + clientName);
                    out.println("Do you want to insert your shared files(M)anually or by (C)onfuguration file?");
                    fromClient=in.readLine();
                    if(fromClient.equalsIgnoreCase("m")){
                      out.println("You chose Manually");
                      manualConfig();
                    }
                    else{
                      out.println("You chose Configuration file");
                    }
                  }
                
                  private void closeConnection() throws IOException{
                    in.close();
                    out.close();
                    connection.close();
                  }
                
                  private void manualConfig() throws IOException{
                    String fileName = clientName+".txt";
                    File file = new File(fileName);
                
                    out.println
                ("Doste onoma, eidos (mp3,txt...),keyword kai megethos arxeioy(bytes)");
                    out.println("Otan teleiwsete patiste ok");
                    try{
                      toFile = new Formatter(fileName);
                      while ((fromClient = in.readLine()) != null){
                        if (fromClient.equalsIgnoreCase("ok")){
                          break;
                        }
                        System.out.println(fromClient);
                        toFile.format(" %s\n", fromClient);
                      }
                    }
                    catch (SecurityException e){
                      System.err.println("You do not have write access");
                      System.exit(1);
                    }
                    catch (FileNotFoundException e){
                      System.err.println("Error creating file");
                      System.exit(1);
                    }
                    finally{
                      toFile.close();
                    }
                  }
                
                  public static void main(String[] args){
                    MyServer m = new MyServer();
                    m.runServer();
                  }
                }
                
                -----------------------------------------------------------------------------
                import java.io.*;
                import java.net.*;
                import java.util.*;
                
                public class Client1{
                  private Socket clientSocket ;
                  private PrintWriter out ;
                  private BufferedReader in ;
                  private Scanner stdIn;
                  private InetAddress host;
                  private String fromServer;
                  private String toServer;
                  private String clientName="Billy";
                
                  public void runClient() throws IOException{
                    host = InetAddress.getLocalHost();
                    try{
                      System.out.println("Attempting to connect...");
                      clientSocket = new Socket(host.getHostName(), 12345);
                      System.out.println("Connected");
                      out = new PrintWriter(clientSocket.getOutputStream(), true);
                      in = new BufferedReader
                        (new InputStreamReader(clientSocket.getInputStream()));
                      System.out.println("Got I/O Streams");
                    }
                    catch (UnknownHostException e){
                      System.err.println("Don't know about host");
                      System.exit(1);
                    }
                    catch (IOException e){
                      System.err.println("Couldn't get I/O for the connection to: Billy.");
                      System.exit(1);
                    }
                    out.println(clientName);
                    fromServer=in.readLine();
                    System.out.println(fromServer);
                    stdIn = new Scanner(System.in);
                    toServer=stdIn.nextLine(); // epilogi "m" or "n"
                    while ((!toServer.equalsIgnoreCase("m")) 
                        && (!toServer.equalsIgnoreCase("c")) ) {
                      System.out.println("You must type m or c");
                    }
                    out.println(toServer);
                    if( toServer.equalsIgnoreCase("m")) {
                      for (int i=0;i<=2;i++){
                        fromServer=in.readLine();
                        System.out.println(fromServer);
                      }
                      manualConfig();
                    }
                    else if ( toServer.equalsIgnoreCase("c")){
                    }
                    out.close();
                    in.close();
                    clientSocket.close();
                  }
                
                  private void manualConfig(){
                    String s = null;
                    Scanner input = new Scanner(System.in);
                
                    while (! (s = input.nextLine()).equalsIgnoreCase("ok")){
                      out.println(s);
                    }
                  }
                
                  public static void main(String[] args) throws Exception{
                    Client1 c = new Client1();
                    c.runClient();
                  }
                }
                • 5. Re: client server application
                  807589
                  thanx for taking the time to read my code and correct it.
                  i have another question if you are so kind as to reply again.


                  the idea for this project is a p2p implementation

                  so the server has a txt with the files that each client has. It proceses the clients request for a file and if someone has it ( i would have 3 clients) the server gives the client the client2 port ( it doesnt need an I.P since all the programs will run from the same pc) and then the client connects to the client2 and gets the file.

                  i know how to copy files through sockes (one byte at a time) but i dont know how to make client1 connect to client2 while client1 is still connected to the server.

                  i have thought to make a class ConnectToClient extends Thread in whitch i will create a Serversocket thsat listens to specific clients port and would wait for connections.

                  any ideas????????

                  Edited by: Billy79 on Aug 31, 2008 4:20 PM
                  • 6. Re: client server application
                    800351
                    Typically a p2p system is that in which each network node behaves both as a client and as a server. If a requirement is so simple, however, a single server in a traditional client/server app could behave as proxies for each of those client-cumm-servers. You should clarify your app level requirement and use scenario.
                    • 7. Re: client server application
                      807589
                      its is a simple napster impementation .
                      there is an index server that has a txt for each client with the files each client has and another txt with the port in whitch the client listens.
                      Each client must say to the index server which files he wants to share manually or throygh a configuration file. the client searches the file he wants and the server checks to see if any client has it. if it is so, the server returns the port in which the client ( lets say client2) having the file listens for connections to client1 and then client1 connects to client2 gets the file and adds the new file to the txt that the server has that contains client1 shared files.

                      i have 2 problems.
                      the first is how to make the 3 clients ( i will have 3 clients) connecting at the same time( dont know anything about multi thread ) and more important how to make client1 connect to client2 while both are still connected to index server

                      the second is how to add to the txt the new info ( in C i can append the txt file, writing the new info at the end)


                      Please help
                      Especially with my first problem on how to connect client1 with client2

                      thanx again

                      Edited by: Billy79 on Aug 31, 2008 5:18 PM
                      • 8. Re: client server application
                        800351
                        Read my reply #6 and do multi-threading both on the server and on the client.

                        For file appending, read the javadoc for java.io classes.
                        • 9. Re: client server application
                          807589
                          so each client must have a server socket also that listens for connections?

                          is it possible to give a simple example on how to do that?
                          • 10. Re: client server application
                            800351
                            Sorry, I'm afraid it can't be that simple. Try yourself and good luck!
                            • 11. Re: client server application
                              807589
                              thanx a lot you have been great help