19

Hi I am using Apache HTTP Client 4.0 to upload some files on a server based on HTTPS protocol. The uploaded application is running 24x7. Today suddenly it started to throw this exception-

java.net.SocketException: No buffer space available (maximum connections reached?): connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(Unknown Source)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:333)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:123)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:147)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:101)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:381)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)

Can anyone please help me? I am totally clueless on what is going on?

This is the source code which upload the file -

public File call() throws Exception {           
            HttpClient httpclient = new DefaultHttpClient();
        try{            
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);         
            /*
             * Create POST REQUEST
             */
            HttpPost httpPost = new HttpPost(this.URL);
            /*
             * Create MultipartRequestEntity
             */
            MultipartEntity multipartEntity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
            /*
             * Add POST Parameters
             */
            multipartEntity.addPart(parameters[0], this.fileBody);
            multipartEntity.addPart(parameters[1], new StringBody(this.TYPE));
            multipartEntity.addPart(parameters[2], new StringBody(this.MAAID));
            /*
             * Add this POST Method
             */
            httpPost.setEntity(multipartEntity);
            /*
             * Upload the file
             */
            HttpResponse response = httpclient.execute(httpPost);
            int responseCode = response.getStatusLine().getStatusCode();
            logger.info("Response Code of HTTP Connectivity ["+ responseCode + "], " +
                                                            "it means ["+ response.getStatusLine().getReasonPhrase()+"]");
            /*
             * Check the server Response
             */
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String status = EntityUtils.toString(entity);
                logger.info("Status of file upload from Server >>"+ status+"<<");
                entity.consumeContent();
                if(status.equalsIgnoreCase("OK")){
                    return this.fileBody.getFile();
                }
            }else{
                logger.error("Unable to retrieve status of file upload from server");
            }           
        }catch(NoRouteToHostException e){
            logger.error("Internet connection to ["+ this.URL + "] is not available", e);
        }catch(SocketException e){
            logger.error("Unable to connect to "+ this.URL, e);
        }catch (Exception e) {          
            logger.error("Exception while uploading the file["+ this.fileBody.getFilename()+ "] on ["+ this.URL+"]", e);
        }finally{
            try{
                httpclient.getConnectionManager().shutdown();
            }catch(Exception e){
                // Ignore this exception
            }
        }
        return null;
    }
user381878
  • 1,543
  • 5
  • 17
  • 30
  • Microsoft windows server 2003, 32 bit machine – user381878 May 20 '11 at 07:05
  • One additional information- logs showed that this exception was thrown 16 times as the main program calls this uploading program everyone hour. On 17th times, it threw a new exception: java.net.BindException: Address already in use: connect – user381878 May 20 '11 at 07:07

5 Answers5

28

My guess: you are running out of ports and the issue isn't directly related to your code but to the current state of your server. Too many connections are opened to other machines and this causes the issue.

What to look for:

  • Is your server under heavy usage that might cause multiple network connections to be opened?
  • The HTTP client documentation recommends to instantiate only one HttpClient and to reuse this instance. They are cases where instantiating multiple HTTP clients and not releasing connections correctly causes network connections to stack and never be closed. Try to httpPost.releaseConnection(). You might also be interested in the HTTP client documentation, chapter 1.1.5, "Ensuring release of low level resources"
Vivien Barousse
  • 20,555
  • 2
  • 63
  • 64
  • 1
    Hi user381878, If this helped you, can you please explain where actually did you make the configuration in server? or did you use - httpPost.releaseConnection() somewhere. – Vikas Kumar Aug 27 '17 at 17:13
  • I am facing a similar problem in UDP program where I am having only one client. The code is working fine when the server and the client codes are both executed on the same machine but not when executed on different machines on the same network. It is showing maximum connections reached. – Samudra Ganguly Nov 16 '21 at 07:24
3

The server has to few "Ephemeral port" defined se following to links : http://dbaktiar-on-java.blogspot.ro/2010/03/hudson-shows-buffer-space-available.html http://support.microsoft.com/kb/196271

This is solved : followed the steps above an "out of sockets" errors are gone.

Issue is limited to 2003 server.

Nicu
  • 43
  • 1
  • 6
  • 4
    Your answer is just a link to an answer; if this link changes, the answer becomes irrelevant. Please post any relevant code/documentation here to make the answer correct. – rfornal Apr 06 '15 at 14:45
  • The KB link _should_ be trusted to be permanent. This is a correct answer for Windows Server 2003. There is a related problem in Windows Server 2008 R2 and R2 SP1. I have collected all the information into a comprehensive answer to a different stackoverflow question that I have posted a link to on this thread. – Derek Bennett Apr 17 '15 at 14:55
  • link is expired :) – Jagadeesh Sep 27 '22 at 13:14
2

This appears to be a Windows issue, either about ephemeral ports, or about a bug in afd.sys, depending on your version of Windows. Please refer to my answer to a similar question on stackoverflow

Community
  • 1
  • 1
Derek Bennett
  • 807
  • 1
  • 7
  • 14
  • Having the same symptoms does not mean you have the same cause. With this type of problem, the cause is different depending on the OS and OS version. This particular occurrence was on Windows Server 2003 32-bit, for which the cause and cure are well-documented, as stated above. – Derek Bennett Mar 09 '16 at 14:59
  • Never had this issue on osx, on windows quite frequent. PS: I am not a apple fan, their glued batteries are not my choice but I love the OS for its stability and reliability. – Martin Pfeffer May 04 '17 at 08:54
1

May happen because Your Server(Database/Http) is exhausted of connections. Use a connection pool or reducing maximum connections can fix this issue.

kanaparthikiran
  • 523
  • 12
  • 15
0

My windows2008 server happened the same issue days ago,I could not fix this problem quickly by coding,and then I rebooted my server the issue be gone,this er