[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

Problem with socket programming

Posted on 2000-02-10
15
Medium Priority
?
232 Views
Last Modified: 2010-04-01
Hello,
    I am writing a socket programming.  The client sends a flat file to the server and the server receives it and then do other stuff.  The problem is that the program(server) seems to stop running at the first part (after the while(!eof) loop).   Then, it doesn't execute the next command as it should.
   If I have everything in the while(!eof) loop, then the next process will be executed  more than once and that is not what I want!
   Please help me and thanks in advance.  

Source sode: (server coding)

public class ServerApp4
{
  public static void main(String []args)
   {
      ServerSocket serverSocket = null;
      Socket clientSocket;
      int noClients = 0;
      StringBuffer strBuffer = new StringBuffer();
      String acc = new String();
      TextFileHandler tfh = new TextFileHandler();
     Conn1 connect = new Conn1();                     
            
       try
      {
         File theFileName = new File("c:\\Temp\\testing2.txt");
        serverSocket = new ServerSocket(1997);
        System.out.println("Server is " +           serverSocket.getInetAddress().getHostName() + "On port number" +           serverSocket.getLocalPort());
       System.out.println("Local Server is up and waiting " + "for          connections..");
          while(true)
      {
                                               //serverSocket.setSoTimeout(50000);
      try
      { /** This is where socket received connection from
          * client.
        **/
      clientSocket = serverSocket.accept();
                                              System.out.println("SERVER: Contacted by " +                           clientSocket.getInetAddress());
      BufferedReader inStream = new BufferedReader(new                   InputStreamReader(clientSocket.getInputStream()));
      DataOutputStream outStream = new                   DataOutputStream(clientSocket.getOutputStream());
      boolean eof = false;
      int lineCount = 0;
      int charCount = 0;
               //String inLine;
//      char[] textArray;
               outStream.writeChars("Data has been successfully sent");
             
                    /** Reading data from stream per line and store
        * it in the textArray.
       **/

         while(!eof)
                 {
                    String inLine = inStream.readLine();
          lineCount ++;
          char[] textArray;
          charCount ++;
                     textArray = inLine.toCharArray();
                                                                                                   
                     /* Write data to the output file */
                     DataOutputStream myFile = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(theFileName)));
                     strBuffer.append(textArray);
                     tfh.appendFile(theFileName, strBuffer);
                                                                                            
                try
                     {  /*Upon receiving po flat file,
                                                                          log file will be created */
             
                                                  String dirName = "c:\\Temp\\";
                                                 String fileName = "po_rec.log";  
                                             //      Date dateRec = new Date();
                                                               
                                              //DateFormat fmt = DateFormat.getDateTimeInstance();
                                              BufferedWriter out = new BufferedWriter(new FileWriter(dirName + fileName, true));                                               acc = strBuffer.toString();  
                                             //System.out.println ("The string: " +acc);                                                       
           if (lineCount == 1)  
      {      
              out.write(acc, 5, 8);  
              out.write(acc, 57, 8);  
              out.write(acc, 125, 8);  
              out.write(acc, 13, 8);  
              out.write(acc, 21, 10);  
      //              out.write(fmt.format(dateRec) );
      }//end if  
                out.close();                                    
      System.out.println ("hello");
        connect.conn1();
                System.out.println ("hello2");

                                                          
       }  //end try
                                      
                catch(IOException e)  
           {  
                                                   System.out.println("Error writing the comp_code in file " + e);  
                                           }
                                     
                                     
               }//end while(!eof)  
               
                  inStream.close();
  //                outStream.close();
                }// end try for listening client    
                           
            catch(InterruptedIOException e){System.err.println("error: " +e);}  
                               
                     
                      }//end while(true)  
                     
           }//end first try    
               
           catch(IOException e)  
           {  
            System.err.println("Error in server : " + e);  
           }  
           finally  
                {  
                  try  
                          {  
                               serverSocket.close();  
                          }  
                  catch(IOException e) {}  
           }// end finally    
 
     }// end main      
                   
 } //end class  
 

 ***the line received (client socket) is more than one.
***the program should receive data and (store it the data in db[will be done by the Conn1]).
***the server will always be 24 hrs running.  
0
Comment
Question by:fareezaa
  • 7
  • 5
  • 2
  • +1
15 Comments
 
LVL 1

Expert Comment

by:rainmal
ID: 2508375
Do no use (while!eof)

Use the following

Sring str = null;

While ((str = inStream.readLine()!=null)
{
   if(str.trim() == null)
      continue;

   //Do whatever you want with str

}

readline will return null whenever it reaches the end of file.
0
 

Expert Comment

by:binkle
ID: 2509580
rainmal is right, eof is signified by readLine returning null. In your original code your loop will continue until an exception is thrown because you never actually change the value of eof inside the while loop, this is why you were getting the no execute/multiple execute behaviour depending on where your code was.
0
 

Expert Comment

by:binkle
ID: 2509582
rainmal is right, eof is signified by readLine returning null. In your original code your loop will continue until an exception is thrown because you never actually change the value of eof inside the while loop, this is why you were getting the no execute/multiple execute behaviour depending on where your code was.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
LVL 4

Expert Comment

by:jerch
ID: 2509912
I didn't see your client code. Anyway, another possible reason is you did not call the flush() method. Probably you're using something that is not autoflush such as BufferedWriter etc.
Because in a BufferedWriter it waits for the buffer to get full before it sends the data to the other machine.
Yes, i also agree with them. You don't use eof.

Hope this helps.
0
 

Author Comment

by:fareezaa
ID: 2510277
Thanks rainmal for the reply.

I've changes to your suggested solution but getting errors:
 The errors:

ServerApp4.java:65: Incompatible type for while. Can't convert java.lang.String to boolean.
                    while((inLine = inStream.readLine()!=null));
                    ^
ServerApp4.java:65: Incompatible type for =. Can't convert boolean to java.lang.String.
                    while((inLine = inStream.readLine()!=null));
                                  ^

Please help me.  I am new to java programming.  Thanks
0
 
LVL 4

Accepted Solution

by:
jerch earned 400 total points
ID: 2510310
add parenthesis

while ((inline = inStream.readLine()) != null)

The reason for that error is that equality has a higher precedence to assignment.  So the solution is to place some parenthesis.

Jerson
0
 

Author Comment

by:fareezaa
ID: 2510495
I got that part solved but i still can't get the next command to run.( after the while loop bracket).  It reads for several times according to how many lines I have and seems to continue endlessly.
I can't get the try loop to run unless I include it in the while loop which I do not want.
The idea is to receive connection from client, read data from stream, create log file, process next class (connect.conn1()), when done, wait for another client.
However, I am now stuck after reading data from stream.
Thanks in advance for the help.
0
 

Author Comment

by:fareezaa
ID: 2515981
Adjusted points to 200
0
 

Author Comment

by:fareezaa
ID: 2515982
Still having the problem.  Eventhough I no longer use the (!eof), it will still keep on running in the while loop and would not loop out and continue to the next process.  Help!! Thanks in advance!
0
 
LVL 4

Expert Comment

by:jerch
ID: 2517339
what is the connect.conn1()?


Jerson
0
 

Author Comment

by:fareezaa
ID: 2517677
conn1 is a class that connects to our database.
It reads from a flat file and insert data into a table in the db.

How do I send an acknowledgement to the client after it receives the data from client? In my program , I use DataOutputStream.  But, it only writes after the server socket is close.  How can I have it writes an acknowledgement right after it accepts the input(data) from client without waiting for the server to close?

Thanks.
0
 
LVL 4

Expert Comment

by:jerch
ID: 2517701
Use the flush() method of the DataOutputStream. This forces any buffered output bytes to be written out to the stream.

outStream.flush()

Jerson
0
 

Author Comment

by:fareezaa
ID: 2517885
nope ..it doesn't work..
i had the outStream.flush() before outStream.close() but it doesn't work..
if i have it after outStream.writeChars("....")
it gives me an exception and automatically close the socket which i do not want it to happen.
0
 
LVL 4

Expert Comment

by:jerch
ID: 2518082
Can you show me your latest code?
You should have the flush after you write in the stream so the flush should be after the writeChars().  By the way, what's the exception thrown?



0
 

Author Comment

by:fareezaa
ID: 2518486
My latest code:

public class ServerApp4b
{
  public static void main(String []args)
   {
     ServerSocket serverSocket = null;
     Socket clientSocket;
     int noClients = 0;
     StringBuffer strBuffer = new StringBuffer();
     String acc = new String();
     TextFileHandler tfh = new TextFileHandler();
     Conn1 connect = new Conn1();            
     try
     {
       File theFileName = new File("c:\\Temp\\testing2.txt");
       serverSocket = new ServerSocket(1997);
       System.out.println("Server is " +          serverSocket.getInetAddress().getHostName() + "On          port number" + serverSocket.getLocalPort());
       System.out.println("Local Server is up and waiting " +           "for connections..");
       while(true)
        { //serverSocket.setSoTimeout(50000);
        try
          { /** This is where socket received connection from
                * client.
                 **/
                                         clientSocket = serverSocket.accept();
             System.out.println("SERVER: Contacted by " +               clientSocket.getInetAddress());
                              BufferedReader inStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                           DataOutputStream outStream = new DataOutputStream(clientSocket.getOutputStream());
                               boolean eof = false;
int lineCount = 0;
int charCount = 0;
//String inLine;
//char[] textArray;
 outStream.writeChars("Data has been successfully     sent");
 outStream.flush();       
            
/** Reading data from stream per line and store
  * it in the textArray.        **/
              String inLine = null;
              System.out.println("Test");
              int loop = 0;
              //while(!eof)
              //   {
                   while((inLine = inStream.readLine())!=null)
                    {
                    if(inLine == null)
                     continue;
                                    lineCount ++;
      char[] textArray;
      charCount ++;
                     textArray = inLine.toCharArray();
                     loop++;
                     System.out.println("Loop: "+loop);                                                                              
                     /* Write data to the output file */
                     DataOutputStream myFile = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(theFileName)));
                     strBuffer.append(textArray);
                     tfh.appendFile(theFileName, strBuffer);
                     myFile.flush();
                          
                try
                     {  /*Upon receiving po flat file,
             log file will be created */
                                     String dirName = "c:\\Temp\\";
       String fileName = "po_rec.log";    
        //      Date dateRec = new Date();  
                                        //DateFormat fmt = DateFormat.getDateTimeInstance();    
       BufferedWriter out = new BufferedWriter(new FileWriter(dirName + fileName, true));      
                                       acc = strBuffer.toString();      
      if (lineCount == 1)      
      {          
          out.write(acc, 5, 8);    
         out.write(acc, 57, 8);      
         out.write(acc, 125, 8);      
         out.write(acc, 13, 8);      
         out.write(acc, 21, 10);      
        //              out.write(fmt.format(dateRec) );  
      }//end if      
                        out.flush();  
      out.close();                              }  //end try    
                                    catch(IOException e)
{      
  System.out.println("Error writing the comp_code in file " + e);      
}    
    }//end while(!eof)    
               System.out.println ("hello");    
              connect.putString(acc);
               connect.conn1();    
               System.out.println ("hello2");    
               inStream.close();
               outstream.close();    
           }// end try for listening client      
                  catch(InterruptedIOException e){System.err.println("error: " +e);}  
   }//end while(true)      
           }//end first try      
            catch(IOException e)    
           {      
            System.err.println("Error in server : " + e);    
           }  
           finally  
                {  
                  try  
                          {  
                               serverSocket.close();  
                          }  
                  catch(IOException e) {}  
           }// end finally    
 
     }// end main      
                   
 } //end class  



*****in this code, I have the outstream.close() after the         while loop, and it doesn't send the outstream string         right away.
***** if I have the outstream.close() after the outStream.flush, it will close the socket connection which I do not want it to be.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month7 days, 15 hours left to enroll

607 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