0

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?

2
  • 2
    You cannot continuously open sockets without closing them. You are exhausting the available file handles. Commented Jul 19, 2013 at 5:30
  • @JimGarrison oh, I've also found a mistake: I create socet twice: firstly in method and then every time I send messages Commented Jul 19, 2013 at 5:38

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.