Fedora Linux Support Community & Resources Center
  #1  
Old 16th April 2010, 05:08 AM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
java.net.SocketException: Too many open files

Dear All,
I am running a java socket application where it reads the data and write to text file and a database at the same time. After some time I get this error? I am totally lost I dont know where is my error? Any help please?

Attached is my code.
Code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;

public class connection5 {
   //public static String dri = "";
   public static int pollCount = 0;
   private ServerSocket serverSocketCon = null;	
   private Socket conn = null;	
   private String port = null;	

   public static void main(String[] args) {

      try {
			    final ServerSocket serverSocket5 = new ServerSocket(9000);
				
				while (true) 
					{
						try 
						{
							
					            
					            Socket conn = serverSocket5.accept();
                                new Thread(new Client1(conn)).start();			            
						}
						catch(Exception e)
						{
									System.out.println(e.toString());
						}
					}
			
      } 
      catch (Exception e) 
      {
         System.out.println(e.toString());
         //System.exit(0); 
      }
   }
   
}
  class Client1 implements Runnable {
    private Socket server;
    private String line,input;

    Client1(Socket server) {
      this.server=server;
    }

 
   //@Override
   public void run() { 
      
      Connection dbconn = null;
      BufferedWriter w = null;
      try {
      
         
         PrintStream out = System.out; 
      	 BufferedWriter fout = null;
         w =  new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
         BufferedReader r = new BufferedReader(new InputStreamReader(server.getInputStream()));
         
        
         

         int m = 0, count=0;
         String line="",ipAdd="",ipPort="";
         String n="";
         w.write("$PA\n");
         w.flush();
         while ((m=r.read()) != 0) 
         {
           	  
           	  DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
              Date dateIn = new Date();
           	  n = n + (char) m;
         	  int i = n.indexOf("GET");
						if(i != -1) { 
							break;
						}
			  
         	  // System.out.println("joinig the N : "+n);
         	  // System.out.println("\nM : "+m);
         	  if (m==35)
         	  {
	         	  
	             String[] result = n.split(",");
	                            
	             Statement stmt = null;
	             
	             
	             w.write("$PA\n");
                 w.flush();
	             
      
			      int count1 = 0;
			      
	              
	              	  DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy");       
                      Date date = Calendar.getInstance().getTime(); 
                      String today = formatter.format(date); 
				      String filename= "MyDataFile"+today+".txt"; 
				      //System.out.println("Filename:"+filename);
                      boolean append = true; 
                 
                      FileWriter fw = new FileWriter(filename,append); 
	                  fw.write(n+"  "+dateFormat.format(dateIn)+"\n");//appends the string to the file 
	                  Date dateOut = new Date();
	                  fw.write("$PA"+"  "+dateFormat.format(dateOut)+"\n");//appends the string to the file 
	                  fw.close();
	                  
	                  
	                  try
			          {
			          
     	                float hdop = 0;
     	                String driverID = "",chksum="";

     					String reportType=result[1].trim();
     					
     					String deviceID=result[3].trim();
     	
     					String dateTime=result[4].trim();
     	
     					String statusBits=result[5].trim();
     	
				        String rssi = statusBits.substring(2,4);
        
				        String mcc = statusBits.substring(4,9);
				        
				        String fullBatStatus=result[6].trim();
				     	
				     	String battVolt=result[6].trim().substring(0,2)+"."+result[6].trim().substring(2,3);
				     	
				     	String ignVolt=result[6].trim().substring(3,5)+"."+result[6].trim().substring(5,6);

				     	String digitalInput=result[7].trim().substring(0,2);
				     	
				     	String digitalOutput=result[7].trim().substring(2,4);
			     	
				     	String[] result2 = result[10].split("'");
				     
				     	String gpsDate = result2[1].trim().substring(0,6);
				     	
				     	String gpsTime = result2[1].trim().substring(6,12);
				     	
				     	String gpsStat = result2[1].trim().substring(12,13);
				     	
				     	String gpsLat = result2[1].trim().substring(13,20);
				     	
				     	String latitude = result2[1].trim().substring(13,20).substring(0,2)+"."+result2[1].trim().substring(13,20).substring(2,7);
				     	
				     	String gpsLong = result2[1].trim().substring(21,29);
				     	
				     	String longitude = result2[1].trim().substring(21,29).substring(0,3)+"."+result2[1].trim().substring(21,29).substring(3,8);
				     	
           
				        Date inDate=null;    
				        DateFormat inDf=new SimpleDateFormat("ddMMyyHHmmss");    
				        inDf.setTimeZone(TimeZone.getTimeZone("UTC")); 
				   
				        try{ 
				      
				        inDate=inDf.parse(dateTime); 
				      
				   
				        }catch(ParseException e)
				        { 
				    
				        } 
				 
						DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
						 
						outDf.setTimeZone(TimeZone.getTimeZone("Asia/Kuala_Lumpur")); 
			  
			  
						String dateTimer=outDf.format(inDate); 
				          
			          
			          	dbconn = DriverManager.getConnection("jdbc:mysql://192.168.1.21:3306/testdb?"+"user=test&password=test12345");
			          	stmt = dbconn.createStatement();
			          
			          	String updateQuery = "UPDATE device SET " + 
							"latitude='" + latitude + 
							"',longitude='" + longitude + 
							"',rssi='" + rssi +
							"',hdop='" + hdop +
							"',dateTimer='" + dateTimer +
							"',gpsStat='" + gpsStat +
							"',battVolt='" + battVolt +
							"',ignVolt='" + ignVolt +
							"',chkSum='" + chksum +
							"',driverID='" + driverID +
						    "',geoFences='" + reportType +		
							"' WHERE serialNumber='" + deviceID + "'";
							
				      count = stmt.executeUpdate(updateQuery);
				      
			          
			          String insertQuery = "INSERT INTO tripData" + 
							"(latitude,longitude,rssi,hdop,dateTimer,gpsStat,battVolt,ignVolt,deviceID,chkSum,driverID,geoFences)" + " VALUES ('" + 
							latitude + "','" + longitude + "','" + rssi + "','" + hdop + "','" + dateTimer + "','"  + gpsStat + "','"  + battVolt + "','" + ignVolt + "','" + deviceID + "','" + chksum + "','"+ driverID + "','"+reportType+"')";
	                  count = stmt.executeUpdate(insertQuery);
			          }
			          catch (SQLException e)  
			          { 
			            System.out.println("Error of insert : "+e);
			          }      

				      finally
				      {
				        try 
				       	{
					        if ( stmt != null ) 
					        {
					          stmt.close();
					        }
				        }
				        catch(SQLException ex){
				       
				        }
				        try 
				       	{
					        if ( dbconn != null ) 
					        {
					          dbconn.close();
					        }
				        }
				        catch(SQLException ex){
				       
				        }
								        
				      }
	             
	             n="";
	            
         	  }
         }
         
	      
      } 
      catch (IOException e)  
      { 
           
      }      

 
      finally
      {
        
        try 
       	{
        
        if ( r != null ) 
        {
          r.close();
        }
        }
        catch(IOException ex){
       
        }
        try 
       	{
        
        if ( w != null ) 
        {
          w.close();
        }
        }
        catch(IOException ex){
       
        }
        try
        {
        
        if(server!=null)
        {
        	server.close();
        }
        }
        catch(IOException ex){
       
        }
        
      }
      
   }
   
   
}

Last edited by Hlingler; 16th April 2010 at 05:28 PM. Reason: Apply [CODE] BB tags.
Reply With Quote
  #2  
Old 16th April 2010, 11:51 AM
giulix Offline
"Fixed" by (vague) request
 
Join Date: Oct 2005
Location: GMT+ 1
Posts: 2,950
linuxfedorafirefox
Re: java.net.SocketException: Too many open files

Please enclose code in CODE tags, not QUOTE tags. I suspect that your r BufferedReader is not in scope when you close it in the finally branch (always null). Move it out of the try statement, like you did for your w BufferedWriter.
I suggest you use some IDE, like Eclipse, which makes spotting these errors (even if this might not be the case) quite simple.
Reply With Quote
  #3  
Old 16th April 2010, 08:19 PM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
Re: java.net.SocketException: Too many open files

Dear Giulix,
I have done accordingly as you wanted my code to be and even put the BufferedReader outside. I still facing the same problem. What else can be my problem? Thank you.
Code:
 
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
 
public class connection5 {
//public static String dri = "";
public static int pollCount = 0;
private ServerSocket serverSocketCon = null; 
private Socket conn = null; 
private String port = null; 
 
public static void main(String[] args) {
 
try {
final ServerSocket serverSocket5 = new ServerSocket(9000);
 
while (true) 
{
try 
{
 
 
Socket conn = serverSocket5.accept();
new Thread(new Client1(conn)).start(); 
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
 
} 
catch (Exception e) 
{
System.out.println(e.toString());
//System.exit(0); 
}
}
 
}
class Client1 implements Runnable {
private Socket server;
private String line,input;
 
Client1(Socket server) {
this.server=server;
}
 
 
//@Override
public void run() { 
 
Connection dbconn = null;
BufferedWriter w = null;
BufferedReader r = null;
try {
 
 
PrintStream out = System.out; 
BufferedWriter fout = null;
w = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
r = new BufferedReader(new InputStreamReader(server.getInputStream()));
 
 
 
 
int m = 0, count=0;
String line="",ipAdd="",ipPort="";
String n="";
w.write("$PA\n");
w.flush();
while ((m=r.read()) != 0) 
{
 
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date dateIn = new Date();
n = n + (char) m;
int i = n.indexOf("GET");
if(i != -1) { 
break;
}
 
// System.out.println("joinig the N : "+n);
// System.out.println("\nM : "+m);
if (m==35)
{
 
String[] result = n.split(",");
 
Statement stmt = null;
 
 
w.write("$PA\n");
w.flush();
 
 
int count1 = 0;
 
 
DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy"); 
Date date = Calendar.getInstance().getTime(); 
String today = formatter.format(date); 
String filename= "MyDataFile"+today+".txt"; 
//System.out.println("Filename:"+filename);
boolean append = true; 
 
FileWriter fw = new FileWriter(filename,append); 
fw.write(n+" "+dateFormat.format(dateIn)+"\n");//appends the string to the file 
Date dateOut = new Date();
fw.write("$PA"+" "+dateFormat.format(dateOut)+"\n");//appends the string to the file 
fw.close();
 
 
try
{
 
float hdop = 0;
String driverID = "",chksum="";
 
String reportType=result[1].trim();
 
String deviceID=result[3].trim();
 
String dateTime=result[4].trim();
 
String statusBits=result[5].trim();
 
String rssi = statusBits.substring(2,4);
 
String mcc = statusBits.substring(4,9);
 
String fullBatStatus=result[6].trim();
 
String battVolt=result[6].trim().substring(0,2)+"."+result[6].trim().substring(2,3);
 
String ignVolt=result[6].trim().substring(3,5)+"."+result[6].trim().substring(5,6);
 
String digitalInput=result[7].trim().substring(0,2);
 
String digitalOutput=result[7].trim().substring(2,4);
 
String[] result2 = result[10].split("'");
 
String gpsDate = result2[1].trim().substring(0,6);
 
String gpsTime = result2[1].trim().substring(6,12);
 
String gpsStat = result2[1].trim().substring(12,13);
 
String gpsLat = result2[1].trim().substring(13,20);
 
String latitude = result2[1].trim().substring(13,20).substring(0,2)+"."+result2[1].trim().substring(13,20).substring(2,7);
 
String gpsLong = result2[1].trim().substring(21,29);
 
String longitude = result2[1].trim().substring(21,29).substring(0,3)+"."+result2[1].trim().substring(21,29).substring(3,8);
 
 
Date inDate=null; 
DateFormat inDf=new SimpleDateFormat("ddMMyyHHmmss"); 
inDf.setTimeZone(TimeZone.getTimeZone("UTC")); 
 
try{ 
 
inDate=inDf.parse(dateTime); 
 
 
}catch(ParseException e)
{ 
 
} 
 
DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
 
outDf.setTimeZone(TimeZone.getTimeZone("Asia/Kuala_Lumpur")); 
 
 
String dateTimer=outDf.format(inDate); 
 
 
dbconn = DriverManager.getConnection("jdbc:mysql://192.168.1.21:3306/testdb?"+"user=test&password=test12345");
stmt = dbconn.createStatement();
 
String updateQuery = "UPDATE device SET " + 
"latitude='" + latitude + 
"',longitude='" + longitude + 
"',rssi='" + rssi +
"',hdop='" + hdop +
"',dateTimer='" + dateTimer +
"',gpsStat='" + gpsStat +
"',battVolt='" + battVolt +
"',ignVolt='" + ignVolt +
"',chkSum='" + chksum +
"',driverID='" + driverID +
"',geoFences='" + reportType + 
"' WHERE serialNumber='" + deviceID + "'";
 
count = stmt.executeUpdate(updateQuery);
 
 
String insertQuery = "INSERT INTO tripData" + 
"(latitude,longitude,rssi,hdop,dateTimer,gpsStat,battVolt,ignVolt,deviceID,chkSum,driverID,geoFences)" + " VALUES ('" + 
latitude + "','" + longitude + "','" + rssi + "','" + hdop + "','" + dateTimer + "','" + gpsStat + "','" + battVolt + "','" + ignVolt + "','" + deviceID + "','" + chksum + "','"+ driverID + "','"+reportType+"')";
count = stmt.executeUpdate(insertQuery);
}
catch (SQLException e) 
{ 
System.out.println("Error of insert : "+e);
} 
 
finally
{
try 
{
if ( stmt != null ) 
{
stmt.close();
}
}
catch(SQLException ex){
 
}
try 
{
if ( dbconn != null ) 
{
dbconn.close();
}
}
catch(SQLException ex){
 
}
 
}
 
n="";
 
}
}
 
 
} 
catch (IOException e) 
{ 
 
} 
 
 
finally
{
 
try 
{
 
if ( r != null ) 
{
r.close();
}
}
catch(IOException ex){
 
}
try 
{
 
if ( w != null ) 
{
w.close();
}
}
catch(IOException ex){
 
}
try
{
 
if(server!=null)
{
server.close();
}
}
catch(IOException ex){
 
}
 
}
 
}
 
 
}
Reply With Quote
  #4  
Old 16th April 2010, 10:07 PM
RupertPupkin Offline
Registered User
 
Join Date: Nov 2006
Location: Detroit
Posts: 5,768
linuxfirefox
Re: java.net.SocketException: Too many open files

There are some things you could do to clean up the code from a Java perspective (like separate the creation of a new thread for each connection in a separate class file). But the error of "too many open files" is an OS issue (assuming you're closing all your sockets and output streams properly...I didn't get a chance to check). The default limit for the number of open file descriptors in Linux is 1024 (at least it is on my Fedora system). You probably hit that limit. You can see what the current limit is with this shell command:
Code:
ulimit -n
And you can increase that limit, say, to 8192, like this:
Code:
ulimit -n 8192
You'll have to do that as the user who owns the Java process you're running, or as root.
Reply With Quote
  #5  
Old 17th April 2010, 09:38 AM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
Re: java.net.SocketException: Too many open files

Dear Rupert,
If you dont mind can you have a look at my code see if I am missing any close because I have close the reader,write,socket connection, file close and even db and statement too. So I dont know what else must I close ? About the file descriptor is it referencing how files I can open at one time is it? The problem my listener is listening for gps data which comes in on a high frequency. So I guess each time data comes in open n close the file and also the db too. Thank you.
Reply With Quote
  #6  
Old 17th April 2010, 11:27 AM
giulix Offline
"Fixed" by (vague) request
 
Join Date: Oct 2005
Location: GMT+ 1
Posts: 2,950
linuxfedorafirefox
Re: java.net.SocketException: Too many open files

Well, since for us it is not so easy to reproduce the kind of input you're dealing with, try first to add debug messages to all the close statements and catch blocks. For example:
Code:
if ( r != null ) {
    r.close();
}
else 
    System.out.println("r is null in 1");
...
catch(IOException ex){
     System.out.println("IOException has been caught in 1");
     ex.printStackTrace();
}
Since you've opened it, it would be an error for it to be null at this point. Do it consistently. Try to isolate the error

Last edited by giulix; 17th April 2010 at 11:34 AM.
Reply With Quote
  #7  
Old 17th April 2010, 03:59 PM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
Re: java.net.SocketException: Too many open files

Dear Guilix,
Thank you for your suggestion. I have one problem is my application is running as a service under the yajsw wrapper. So where will it be printed then for me to check? Thank you.

---------- Post added at 05:59 AM CDT ---------- Previous post was at 05:29 AM CDT ----------

Dear Gulix,
I tried you method ulimit -n 8192 but after I logged it still remain as 1024. Then I tried ulimit -c 8192 now it shows unlimited each time I login this is dangeorus rite. Can you help me please ?
Reply With Quote
  #8  
Old 17th April 2010, 07:51 PM
giulix Offline
"Fixed" by (vague) request
 
Join Date: Oct 2005
Location: GMT+ 1
Posts: 2,950
linuxfedorafirefox
Re: java.net.SocketException: Too many open files

I know nothing about yajsw. You'll have to have a look at its documentation. I suggest you implement some logging mechanism, as soon as you have the time. Have a look at Log4j, it's pretty standard...
Reply With Quote
  #9  
Old 17th April 2010, 08:04 PM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
Re: java.net.SocketException: Too many open files

Dear Giulix,
Thank you.How about ulimit value I still set using the ulimit -n 8192 but it after I logout n login it reapaper as 1024 how to permanantely fix it? I have something interesting I jsut notice that there is quite a lot of CLOSE_WAIT why ya ? So log tool you gave me it will automatically log is it?
Reply With Quote
  #10  
Old 17th April 2010, 09:08 PM
giulix Offline
"Fixed" by (vague) request
 
Join Date: Oct 2005
Location: GMT+ 1
Posts: 2,950
linuxfedorafirefox
Re: java.net.SocketException: Too many open files

Nope, there's some work to be done.
1) Download the package from Apache foundation and extract the log4j-1.2.16.jar archive from the tarball or zip file and put it into your build directory
2) Define a log4j.properties file for your appllication. In the example case the application is called Pippo

log4j.properties
Code:
log4j.rootLogger=DEBUG
# FileAppender - used to log messages to a log file
log4j.appender.MyFileAppender=org.apache.log4j.FileAppender
 
log4j.appender.MyFileAppender.File=file.log
 
log4j.appender.MyFileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.MyFileAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
 
log4j.logger.Pippo=DEBUG,MyFileAppender
And this is the application:

Pippo.java
Code:
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Pippo {

    public static void main(String[] args) {

        Logger log = Logger.getLogger(Pippo.class);
        PropertyConfigurator.configure("log4j.properties");
        log.debug("Debug log message");
        log.info("Info log message");
        log.warn("Warn log message");
        log.error("Error log message");
        log.fatal("Fatal log message");
    }

}
Compile with:
Code:
javac -cp ./log4j-1.2.16.jar:. Pippo.java
Run with:
Code:
java -cp ./log4j-1.2.16.jar:. Pippo


---------- Post added at 09:08 PM CDT ---------- Previous post was at 08:33 PM CDT ----------

For debug messages, this is the preferred syntax
Code:
if(log.isDebugEnabled())
    log.debug("This is a debug message");
as it is less costly in terms of CPU cycles
Reply With Quote
  #11  
Old 17th April 2010, 09:12 PM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
Re: java.net.SocketException: Too many open files

Dear Guilix,
Never mind I will try your method too but can you help to guide me how to set pemanently the ulimit -n ? Thank you.
Reply With Quote
  #12  
Old 17th April 2010, 10:29 PM
giulix Offline
"Fixed" by (vague) request
 
Join Date: Oct 2005
Location: GMT+ 1
Posts: 2,950
linuxfedorafirefox
Re: java.net.SocketException: Too many open files

Put the ulimit command Rupert gave you in your .bashrc (that's the default initialization script for all sessions opened with your user and is located in your home dir). I don't think that setting it at the root level is a good idea and given the amount of input you're dealing with, I don't think it's going to do any good unless you correct the problem

---------- Post added at 10:29 PM CDT ---------- Previous post was at 09:44 PM CDT ----------

After double-checking, I discovered that it is not allowed for a "normal" user to increase its hard limit: As root, edit the file /etc/security/limits.conf and add the following line before the "# End of file" marker:
Code:
your_username		hard	nofile		nnnn
substitute your_username and nnnn with appropriate values

Then, as your "normal" user, add the following line to your .bashrc script, which can be found in your home directory (/home/your_username):
Code:
ulimit -n nnnn
where nnnn is your new open files limit
Reply With Quote
  #13  
Old 18th April 2010, 10:13 AM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
Re: java.net.SocketException: Too many open files

Dear Guilix,
I have added the extra error message as per your suggestion earlier. Below is some errors and also my code.

java.io.FileNotFoundException: MyDataFile.txt (Too many open files) (line 127)
IOException has been caught in in the file operation (line 127)
fw is null in finally close (145)
Error of insert : com.mysql.jdbc.exceptions.jdbc4.CommunicationsExce ption: Communications link failure(250)
Reply With Quote
  #14  
Old 18th April 2010, 10:18 AM
newbie14 Offline
Registered User
 
Join Date: Feb 2010
Posts: 109
windows_xp_2003ie
Re: java.net.SocketException: Too many open files

Here is the updated code

Code:
import java.io.*;
import java.net.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;

public class connection5 {

   public static int pollCount = 0;
   private ServerSocket serverSocketCon = null;	
   private Socket conn = null;	
   private String port = null;	

   public static void main(String[] args) {
      try {
			    final ServerSocket serverSocket5 = new ServerSocket(9000);				
				while (true) 
					{
						try 
						{
												            Socket conn = serverSocket5.accept();
                                new Thread(new Client1(conn)).start();			            
						}
						catch(Exception e)
						{
								System.out.println(e.toString());
						}
					}
			
      } 
      catch (Exception e) 
      {
         System.out.println(e.toString());
         //System.exit(0); 
      }
   }
   
}
  class Client1 implements Runnable {
    private Socket server;
    private String line,input;

    Client1(Socket server) {
      this.server=server;
    }

   //@Override
   public void run() { 
      
      Connection dbconn = null;
      BufferedWriter w = null;
      BufferedReader r = null;
      try {             
         PrintStream out = System.out; 
      	 BufferedWriter fout = null;
         w =  new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
         r = new BufferedReader(new InputStreamReader(server.getInputStream()));
         
         int m = 0, count=0;
         String line="",ipAdd="",ipPort="";
         String n="";
         w.write("$PA\n");
         w.flush();
         while ((m=r.read()) != 0) 
         {
           	  
           	  DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
              Date dateIn = new Date();
           	  n = n + (char) m;
         	  int i = n.indexOf("GET");
						if(i != -1) { 
							break;
						}
			  

         	  if (m==35)
         	  {
	         	  
	             String[] result = n.split(",");
	                            
	             Statement stmt = null;
	             
	             
	             w.write("$PA\n");
                 w.flush();
	             
      
			      int count1 = 0;
			      
			                   	  DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy");       
                      Date date = Calendar.getInstance().getTime(); 
                      String today = formatter.format(date); 
				      String filename= "MyDataFile.txt"; 

                      boolean append = true; 
                      
                      FileWriter fw = null;
                      try
                      {
                      
                      fw = new FileWriter(filename,append); 
	                  fw.write(n+"  "+dateFormat.format(dateIn)+"\n");
	                  Date dateOut = new Date();
	                  fw.write("$PA"+"  "+dateFormat.format(dateOut)+"\n");
                      }
                      catch (IOException ex)  
				      { 
				           System.out.println("IOException has been caught in in the file operation");
				           ex.printStackTrace();
				      }      

 
      				  finally
      				  {
        
        				try 
       				   {
        
	                   if ( fw != null ) 
	                   {
	          	       fw.close();
	                   }
	                   else 
	                   {
	        	       System.out.println("fw is null in finally close");
	                   }
       
                       }
				        catch(IOException ex){
				           System.out.println("IOException has been caught in r is null in finally close");
				           ex.printStackTrace();
				
				        }
      				  }
        
	                  try
			          {
			          
     	                float hdop = 0;
						String driverID = "",chksum="";
						 
						String reportType=result[1].trim();
						 
						String deviceID=result[3].trim();
						 
						String dateTime=result[4].trim();
						 
						String statusBits=result[5].trim();
						 
						String rssi = statusBits.substring(2,4);
						 
						String mcc = statusBits.substring(4,9);
						 
						String fullBatStatus=result[6].trim();
						 
						String battVolt=result[6].trim().substring(0,2)+"."+result[6].trim().substring(2,3);
						 
						String ignVolt=result[6].trim().substring(3,5)+"."+result[6].trim().substring(5,6);
						 
						String digitalInput=result[7].trim().substring(0,2);
						 
						String digitalOutput=result[7].trim().substring(2,4);
						 
						String[] result2 = result[10].split("'");
						 
						String gpsDate = result2[1].trim().substring(0,6);
						 
						String gpsTime = result2[1].trim().substring(6,12);
						 
						String gpsStat = result2[1].trim().substring(12,13);
						 
						String gpsLat = result2[1].trim().substring(13,20);
						 
						String latitude = result2[1].trim().substring(13,20).substring(0,2)+"."+result2[1].trim().substring(13,20).substring(2,7);
						 
						String gpsLong = result2[1].trim().substring(21,29);
						 
						String longitude = result2[1].trim().substring(21,29).substring(0,3)+"."+result2[1].trim().substring(21,29).substring(3,8);
						 
						 
						Date inDate=null; 
						DateFormat inDf=new SimpleDateFormat("ddMMyyHHmmss"); 
						inDf.setTimeZone(TimeZone.getTimeZone("UTC")); 
						 
						try{ 
						 
						inDate=inDf.parse(dateTime); 
						 
						 
						}catch(ParseException e)
						{ 
						 
						} 
						 
						DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
						 
						outDf.setTimeZone(TimeZone.getTimeZone("Asia/Kuala_Lumpur")); 
						 
						 
						String dateTimer=outDf.format(inDate); 
						 
						 
						dbconn = DriverManager.getConnection("jdbc:mysql://192.168.1.21:3306/testdb?"+"user=test&password=test12345");
						stmt = dbconn.createStatement();
 
						String updateQuery = "UPDATE device SET " + 
						"latitude='" + latitude + 
						"',longitude='" + longitude + 
						"',rssi='" + rssi +
						"',hdop='" + hdop +
						"',dateTimer='" + dateTimer +
						"',gpsStat='" + gpsStat +
						"',battVolt='" + battVolt +
						"',ignVolt='" + ignVolt +
						"',chkSum='" + chksum +
						"',driverID='" + driverID +
						"',geoFences='" + reportType + 
						"' WHERE serialNumber='" + deviceID + "'";
						 
						count = stmt.executeUpdate(updateQuery);
						 
						 
						String insertQuery = "INSERT INTO tripData" + 
						"(latitude,longitude,rssi,hdop,dateTimer,gpsStat,battVolt,ignVolt,deviceID,chkSum,driverID,geoFences)" + " VALUES ('" + 
						latitude + "','" + longitude + "','" + rssi + "','" + hdop + "','" + dateTimer + "','" + gpsStat + "','" + battVolt + "','" + ignVolt + "','" + deviceID + "','" + chksum + "','"+ driverID + "','"+reportType+"')";
						count = stmt.executeUpdate(insertQuery);
			          }
			          catch (SQLException e)  
			          { 
			            System.out.println("Error of insert : "+e);

			          }      

				      finally
				      {
				        try 
				       	{
					        if ( stmt != null ) 
					        {
					          stmt.close();
					        }
					        else 
					        {
					        	System.out.println("stmt is null in finally close");
					        }
				        }
				        catch(SQLException ex){
				             System.out.println("SQLException has been caught for stmt close");
                             ex.printStackTrace();
				        }
				        try 
				       	{
					        if ( dbconn != null ) 
					        {
					          dbconn.close();
					        }
					        else 
					        {
					        	System.out.println("dbconn is null in finally close");
					        }
				        }
				        catch(SQLException ex){
				             System.out.println("SQLException has been caught for dbconn close");
                             ex.printStackTrace();
				        }
								        
				      }
	              
	             
	             n="";
	            
         	  }
         }
         
	      
      } 
      catch (IOException ex)  
      { 
           System.out.println("IOException has been caught in in the main first try");
           ex.printStackTrace();
      }      

 
      finally
      {
        
        try 
       	{
        
	        if ( r != null ) 
	        {
	          	r.close();
	        }
	        else 
	        {
	        	System.out.println("r is null in finally close");
	        }
       
        }
        catch(IOException ex){
           System.out.println("IOException has been caught in r is null in finally close");
           ex.printStackTrace();

        }
        try 
       	{
        
	        if ( w != null ) 
	        {
	          	w.close();
	        }
	        else 
	        {
	        	System.out.println("w is null in finally close");
	        }
        }
        catch(IOException ex){
           System.out.println("IOException has been caught in w is null in finally close");
           ex.printStackTrace();
        }
        try
        {
        
	        if(server!=null)
	        {
	        	server.close();
	        }
	        else 
	        {
	        	 System.out.println("server is null in finally close");
	        }
        }
        catch(IOException ex){
           System.out.println("IOException has been caught in socket close is null in finally close");
           ex.printStackTrace();
        }
        
      }
      
   }
   
   
}
Reply With Quote
  #15  
Old 18th April 2010, 11:44 AM
giulix Offline
"Fixed" by (vague) request
 
Join Date: Oct 2005
Location: GMT+ 1
Posts: 2,950
linuxfedorafirefox
Re: java.net.SocketException: Too many open files

Apparently, you're still hitting the max open files limit, therefore fw is null... that is what the exception and the message "fw is null in finally close" seem to point at. It's difficult to determine whether the error is due to files left open or because of the large amount of input data. There are some things that you can do to improve your code, though. For example, avoid opening fw in the while loop: Since you're appending to it, open it before entering the loop and close it afterwards. Refactor your code: Put the database operations in a separate class to isolate them, like Rupert suggested. Clean it up a bit... Then my advice is not to add complexity until you've solved the 'too many open files' problem, otherwise it will get double complicated to fix it. As a matter of fact, a good strategy would be to cut down your present code to the minimum amount of statements that makes it fail, fix it and only then add more complexity

Last edited by giulix; 18th April 2010 at 11:49 AM.
Reply With Quote
Reply

Tags
files, javanetsocketexception, open

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
How do I un-install the open source Java in Fedora 9 kumudini Using Fedora 3 9th September 2008 05:59 AM
F7, Open Office, Java and Nautilus nicstevens42 Using Fedora 5 12th August 2007 07:04 PM
files want to open with java.... StevenMedley Using Fedora 1 4th July 2007 03:05 AM
How will an Open Source Java effect linux? KClaisse Linux Chat 9 28th October 2006 06:51 AM
good news- open source of JAVA and ATI drivers steve941 Using Fedora 2 16th August 2006 01:59 PM


Current GMT-time: 18:17 (Friday, 19-12-2014)

TopSubscribe to XML RSS for all Threads in all ForumsFedoraForumDotOrg Archive
logo

All trademarks, and forum posts in this site are property of their respective owner(s).
FedoraForum.org is privately owned and is not directly sponsored by the Fedora Project or Red Hat, Inc.

Privacy Policy | Term of Use | Posting Guidelines | Archive | Contact Us | Founding Members

Powered by vBulletin® Copyright ©2000 - 2012, vBulletin Solutions, Inc.

FedoraForum is Powered by RedHat
Creek Side - Stockholm-Arlanda Airport (ARN) Travel Photos on Instagram - Marina of Koper Travel Photos - Te Whiti Park Instagram Photos - Texas State Fair Photos on Instagram