Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 222
  • Last Modified:

from client i can send only first request to server

Dear experts,

I'm writting client server application ...from client side i need to send serveral request to server atfter connection is established!
let say my first command need to submit to server and get result back to anylize and find out what will send next and next ... the problem is
when i get result back from my first request the next command seem not interact by server... what is wrong?

thanks,
0
ikhmer
Asked:
ikhmer
  • 5
  • 4
  • 2
  • +3
1 Solution
 
Ajay-SinghCommented:
you need to flush the client request and make sure that it is read my the server completely and vice-versa.
0
 
CEHJCommented:
ikhmer - you seem to be posting quite a few questions and accepting answers, yet you're still asking fundamental questions ..?
0
 
ikhmerAuthor Commented:
i already use flush!!! but from server side seem does nothing with second request!

Well Cehj, if i know all about it i won't ask you any question and do you know why i pay for this site???
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
CEHJCommented:
OK. You need to post some code (as little as possible)
0
 
enachemcCommented:
You need to use HTTP keep-alives (client and server) if you want to process more requests per connection. Be aware that for keep-alives to work, the size of the response must be known when the header is sent (and sent along with the header).
0
 
reach2piyushCommented:
By client server application, do you mean a HTTP based web application with Servlets JSPs etc.??
0
 
ikhmerAuthor Commented:
not use HTTP-- i'm using normal console mode! below is apart of my server side code:
from client i want to send more than one comment and getback result before sending next command.

  public void run() {
 
    while (true) {
          
      try {
        Socket mySocket = theServer.accept();        
        System.out.println("Client request is accepted!!!");                      
        PrintWriter out = new PrintWriter(coreSocket.getOutputStream(), true);              
        BufferedReader in = new BufferedReader(new InputStreamReader(coreSocket.getInputStream()), 1024 );  
                             
              try{                       
                     String n = in.readLine();                               
                      if (n == null) break;    
                      
                      System.out.println("Client said: " + n );
                      getInputVal = n.split(" ");
                      
                      xxx=getInputVal[0];
                      yyy =getInputVal[1];  
               }
               catch (IOException ex) {
                        System.err.println(ex);    
               }  
               
               //***get connection parameter to upper server (...)
                try{
                        myDb_pooling db_pooling= new myDb_pooling();
                      db_pooling.myConn();
                
                      getHost_para=db_pooling.get_host_para("444").trim();
                                            
                      getPara_val=getHost_para.split("@@@");                                            
                      for (j=0;j<getPara_val.length;j++){
                            System.out.println(j + ":::: " +getPara_val[j]);
                      }
                      
                      Socket upServer = new Socket(192.168.0.1,4444);
                    PrintWriter outS = new PrintWriter(upServer.getOutputStream(),true);
                    BufferedReader inS  = new BufferedReader(new InputStreamReader(upServer.getInputStream()),1024);
              
                      /** Login to Upperser(s) **/
                    if(upServer.isConnected()) {                              
                           outS.println("lgi user:iUser,pwd:ipwd");
                           outS.flush();                           
                     }
               
                     outS.println("chk info:id=\"" + yyy + "\";");
                      outS.flush();  
                      
                      while ( (upSvr_out = inS.readLine()) != null ) {                                                               
                            out.println(upSvr_out);                                                                 
                            out.flush();
                                                  
                        if (upSvr_out.indexOf("Total") != -1) break;
                  }
      
                  
                  outS.close();
                  inS.close();
                  upServer.close();
                      
                }
                catch (Exception e) {
                        e.printStackTrace(System.err);
                        System.exit(-1);
               }
                     
                     
        out.close();
        in.close();
        mySocket.close();
       
      }  
      catch (IOException ex) {
            System.err.println(ex);
      }
     }  
  }  
 
0
 
bondzoroCommented:
I see that you are reading data only once from client and you are not reading the data from the client processing it and closing the stream

Simple way to implement this is by the method all universal protocols follow.
i.e by sending "\r\n"
from the cleint side if you think all parameters are sent then send signal "\r\n"
on sevrer side if received "\r\n" then server knows everything has been received.
Also in above code there is an error you are reading data from cleint only once .

your code is as follows

First of all its not multi-thread model .

while(true)
->accpeting a connection
-> opening input/output streams to perform r/w operations
-> reading data from cleint
-> processing data
-> close all streams
} - end of while

this means you are reading only one line

while(true) { //main while
 ->accpeting a connection
-> opening input/output streams to perform r/w operations
  while(!='\r\n') { //inner while till you read complete data or one by one
 -> reading data from cleint
 -> process data
  }//end of inner while
  close streams
  close socket
}//main while end


To make this multi thread model
one you open accept a new connection spawn a new thread by passing accpted socket as parameter to the new thread class.
this would be more efficient .


Hope this helps -
bond
0
 
ikhmerAuthor Commented:
in main class already extends thread! and if i use >>  while(!='\r\n') it get only first command and loop forever!!!
0
 
bondzoroCommented:
your client should send '\r\n'
after you read data put an explict condition or add this method which reads data from input stream and returns string

 public String readRequest() throws IOException{
      String request = "";
      for(int b; (b = in.read()) != -1;) {
         if((char) b == '\r');
         else if((char) b == '\n') {
            break;
         } else request += (char) b;
      }
      return request.trim();
   }


0
 
bondzoroCommented:
even though your main class is extending thread that is not serving the purpose
we need to implement something very similar to webserver . I.e process each and every request independently and also handle any errors/exceptions
gracefully.

In the new implememtaion I have Architected your solution in different way .


MainServer class

1) Extends thread
   constructer takes port on which to starts the server on that port

    public MainServer(int port) throws InterruptedException{
      try {
         sop("Attempting to initialize SMS service on port "+port);
         server =  new ServerSocket(port);
         this.start();
         sop("Startup complete!!!");
      } catch(IOException _ioe) {
         sop("Server could not be started on specified port");
      }
   }//MainServer cons

2) in RUN method Accept socket connection and spawn a new thread (inner/external class) which takes socket as parameter in constructer . Lets call this class

WorkerThread (will draft this how to handle this below
  code snippet
   public void run() {
      sop("listening to client requests.");
      while(true) {
         try {
            Socket client = server.accept();
            sop("serving request from "+client);
            new WorkerThread(client).start();
            sleep(10000);
         } catch(IOException _ioe) {
            _ioe.printStackTrace();
            sop("Unable to accept connections.");
         } catch(InterruptedException _ie) {
            _ie.printStackTrace();
            sop("Unable to accept connections.");
         }
      }


3) WorkerThread (inner class or a new external class)
   Class WorkerThread extends Thread
   Socket client = null;
   DataInputStream in ;
   PrintStream out ;

  //constructer
   public SMSServerThread(Socket client) {
      this.client = client;
   }

  public String readRequest() throws IOException{
      String request = "";
      for(int b; (b = in.read()) != -1;) {
         if((char) b == '\r');
         else if((char) b == '\n') {
            break;
         } else request += (char) b;
      }
      return request.trim();
   }


 //since we have already started this thread from mainserver we will be in run method of workerthread class

 public void run(){
  //open input
  //read request using readRequest method posted above.
   while(!(clientRequest=readRequest()).equals("")) {
    //process data and write data to cleint connected
   }
   
  close output/input streams;
  close the socket.
 }



4) Client class

  -> open socket connetion on IP:port
  -> write all data and at the end send '\r\n' indicating the end of data .
  -> read data from inputstream (client class which is output stream in server class).
  -> server also sends '\r\n' indicating end of data
  -> close the connection
 

In this I have sent all the data from the client at a stretch and terminated the request by cleint by '\r\n' to server.
however you can make minor modifications to suit your needs in sevrer/client class to send request multiple times.
Hope this helps
0
 
ikhmerAuthor Commented:
thank for your good idea! and if i have two while(true) , eg:

while(true) {  // #1
...
...
  while(true){  //#2
  ...
     if ( )  break; // want to break out from #2 only

  ...
  }
...
...
}


--> if i issue break statement in #2 it will exit from main while (#1) also! how to break from #2 only? so, the next process will keep running on while #1(main while)
0
 
bondzoroCommented:
Here is a simple class which illustrates how to break inner/outer loops..

class x {
   public static void main(String a[]){
      int i=0;
      int j=0;
outer: while(true) {
          System.out.println("outer");
          if(i==2) {
             System.out.println("breaking outer");
             break outer;
          }
inner: while(true) {
          System.out.println("inner "+j+":"+i);
          j++;
          if(j==2){
             i++;
             System.out.println("breaking inner i:" +i + ":j"+j);
             j=0;
             break inner;
          }
       }//inner
       }//outer
   }//main
}//class x

Hope this helps
0
 
ikhmerAuthor Commented:
Many thanks!!!
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 4
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now