Solved

from client i can send only first request to server

Posted on 2006-11-14
14
207 Views
Last Modified: 2010-03-31
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
Comment
Question by:ikhmer
  • 5
  • 4
  • 2
  • +3
14 Comments
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 17945024
you need to flush the client request and make sure that it is read my the server completely and vice-versa.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 17945033
ikhmer - you seem to be posting quite a few questions and accepting answers, yet you're still asking fundamental questions ..?
0
 

Author Comment

by:ikhmer
ID: 17945048
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 17945066
OK. You need to post some code (as little as possible)
0
 
LVL 12

Expert Comment

by:enachemc
ID: 17945100
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
 
LVL 8

Expert Comment

by:reach2piyush
ID: 17945198
By client server application, do you mean a HTTP based web application with Servlets JSPs etc.??
0
 

Author Comment

by:ikhmer
ID: 17945482
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 1

Expert Comment

by:bondzoro
ID: 17945757
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
 

Author Comment

by:ikhmer
ID: 17946054
in main class already extends thread! and if i use >>  while(!='\r\n') it get only first command and loop forever!!!
0
 
LVL 1

Expert Comment

by:bondzoro
ID: 17946133
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
 
LVL 1

Accepted Solution

by:
bondzoro earned 500 total points
ID: 17946280
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
 

Author Comment

by:ikhmer
ID: 17973794
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
 
LVL 1

Expert Comment

by:bondzoro
ID: 17977327
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
 

Author Comment

by:ikhmer
ID: 17977608
Many thanks!!!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now