Reputation: 3019
I'm studying java.net and created a simple app which transmits files. I takes files from disk, transform them to the byte[]
and here is the problem after a few minutes working it drops the folowing:
init error: java.net.SocketException: Too many open files
java.lang.NullPointerException
on every attempt to send the file.
CODE:
public class Main extends Thread {
public static final FilesGetter filesGetter = new FilesGetter();
public static Socket s;
public static File[] files;
public static void main(String args[]) throws Exception{
s = new Socket("localhost", 3128);
while (true){
try{
files = filesGetter.getFilesList("/etc/dlp/templates/");
Socket s = new Socket("localhost", 3128);
args[0] = args[0]+"\n"+s.getInetAddress().getHostAddress()
+":"+s.getLocalPort();
if (files != null){
for (int i = 0; i < files.length; i++){
InputStream is = new FileInputStream(files[i]);
byte[] message = IOUtils.toByteArray(is);
s.getOutputStream().write(message);
byte buf[] = new byte[128*1024];
int r = s.getInputStream().read(buf);
String data = new String(buf, 0, r);
System.out.println(data);
}
}
} catch(Exception e){
System.out.println("init error: "+e);
}
}
}
how to solve this?
Upvotes: 0
Views: 1598
Reputation: 86774
You have a loop in which you open a new socket on each iteration. You never seem to close any of the sockets. They may get closed when the out-of-scope objects are GC'ed, but you are creating these sockets at a very high rate and exhausting the available file handles.
Close each socket when you are done with it.
Upvotes: 3