Java net socketexception software caused connection abort socket write error

Given this stack trace snippet Caused by: java.net.SocketException: Software caused connection abort: socket write error  at java.net.SocketOutputStream.socketWrite0(Native Method) I

Given this stack trace snippet

Caused by: java.net.SocketException:
Software caused connection abort:
socket write error
 at
java.net.SocketOutputStream.socketWrite0(Native
Method)

I tried to answer the following questions:

  1. What code is throwing this exception? (JVM?/Tomcat?/My code?)
  2. What causes this exception to be thrown?

Regarding #1:

Sun’s JVM source doesn’t contain this exact message, but I think the text Software caused connection abort: socket write error is from the native implementation of SocketOutputStream:

private native void socketWrite0(FileDescriptor fd, byte[] b, int off,
                 int len) throws IOException;

Regarding #2

My guess is that it is caused when the client has terminated the connection, before getting the full response (e.g. sent a request, but before getting the full response, it got closed / terminated / offline)

Questions:

  1. Are the above assumptions correct (#1 and #2)?
  2. Can this be diffrentiated from the situation: «could not write to the client, due to a network error on the server side»? or would that render the same error message?
  3. And most important: Is there an official document (e.g from Sun) stating the above?

I need to have a proof that this stack trace is the socket client’s «fault», and there is nothing that the server could have done to avoid it. (except catching the exception, or using a non Sun JVM SocketOutputStream, though both don’t really avoid the fact the client has terminated)

asked Jan 24, 2010 at 9:52

Eran Medan's user avatar

Eran MedanEran Medan

43.9k61 gold badges182 silver badges275 bronze badges

4

The java.net.SocketException is thrown when there is an error creating or accessing a socket (such as TCP). This usually can be caused when the server has terminated the connection (without properly closing it), so before getting the full response. In most cases this can be caused either by the timeout issue (e.g. the response takes too much time or server is overloaded with the requests), or the client sent the SYN, but it didn’t receive ACK (acknowledgment of the connection termination). For timeout issues, you can consider increasing the timeout value.

The Socket Exception usually comes with the specified detail message about the issue.

Example of detailed messages:

  • Software caused connection abort: recv failed.

    The error indicates an attempt to send the message and the connection has been aborted by your server. If this happened while connecting to the database, this can be related to using not compatible Connector/J JDBC driver.

    Possible solution: Make sure you’ve proper libraries/drivers in your CLASSPATH.

  • Software caused connection abort: connect.

    This can happen when there is a problem to connect to the remote. For example due to virus-checker rejecting the remote mail requests.

    Possible solution: Check Virus scan service whether it’s blocking the port for the outgoing requests for connections.

  • Software caused connection abort: socket write error.

    Possible solution: Make sure you’re writing the correct length of bytes to the stream. So double check what you’re sending. See this thread.

  • Connection reset by peer: socket write error / Connection aborted by peer: socket write error

    The application did not check whether keep-alive connection had been timed out on the server side.

    Possible solution: Ensure that the HttpClient is non-null before reading from the connection.E13222_01

  • Connection reset by peer.

    The connection has been terminated by the peer (server).

  • Connection reset.

    The connection has been either terminated by the client or closed by the server end of the connection due to request with the request.

    See: What’s causing my java.net.SocketException: Connection reset?

Community's user avatar

answered Aug 25, 2016 at 11:11

kenorb's user avatar

kenorbkenorb

149k80 gold badges668 silver badges723 bronze badges

1

I have seen this most often when a corporate firewall on a workstation/laptop gets in the way, it kills the connection.

eg. I have a server process and a client process on the same machine. The server is listening on all interfaces (0.0.0.0) and the client attempts a connection to the public/home interface (note not the loopback interface 127.0.0.1).

If the machine is has its network disconnected (eg wifi turned off) then the connection is formed. If the machine is connected to the corporate network (directly or vpn) then the connection is formed.

However, if the machine is connected to a public wifi (or home network) then the firewall kicks in an kills the connection. In this situation connecting the client to the loopback interface works fine, just not to the home/public interface.

Hope this helps.

akjoshi's user avatar

akjoshi

15.1k13 gold badges104 silver badges120 bronze badges

answered Jan 31, 2013 at 11:46

user2028913's user avatar

1

To prove which component fails I would monitor the TCP/IP communication using wireshark and look who is actaully closing the port, also timeouts could be relevant.

answered Jan 24, 2010 at 11:01

stacker's user avatar

stackerstacker

67.5k27 gold badges140 silver badges209 bronze badges

3

For anyone using simple Client Server programms and getting this error, it is a problem of unclosed (or closed to early) Input or Output Streams.

answered Nov 25, 2014 at 7:33

PRO_gramista's user avatar

PRO_gramistaPRO_gramista

9221 gold badge9 silver badges25 bronze badges

1

Have you checked the Tomcat source code and the JVM source ? That may give you more help.

I think your general thinking is good. I would expect a ConnectException in the scenario that you couldn’t connect. The above looks very like it’s client-driven.

answered Jan 24, 2010 at 9:57

Brian Agnew's user avatar

Brian AgnewBrian Agnew

266k36 gold badges331 silver badges439 bronze badges

7

I was facing the same issue.
Commonly This kind of error occurs due to client has closed its connection and server still trying to write on that client.
So make sure that your client has its connection open until server done with its outputstream.
And one more thing, Don`t forgot to close input and output stream.

Hope this helps.
And if still facing issue than brief your problem here in details.

answered Jun 28, 2016 at 11:41

Nirav Chhatrola's user avatar

1

Had an SSLPoke.bat (SSL troubleshooting script) window script that was getting this error despite importing the correct certificates into the cacerts trustore.

C:Javajdk1.8.0_111jrelibsecurity>SSLPoke.bat

C:Javajdk1.8.0_111jrelibsecurity>"C:jdk1.8.0_101jrebinjava" 
     `SSLPoke  tfs.corp.****.com  443`

java.net.SocketException: Software caused connection abort: recv failed
    `at java.net.SocketInputStream.socketRead0(Native Method)`
    `at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)`
    `at java.net.SocketInputStream.read(SocketInputStream.java:170)`
    `at java.net.SocketInputStream.read(SocketInputStream.java:141)`
    `at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)`
    `at sun.security.ssl.InputRecord.read(InputRecord.java:503)`
    `at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)`
    `at sun.security.ssl.SSLSocketImpl.performInitialHandshake
       (SSLSocketImpl.java:1375)`
    `at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)`
    `at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)`
    `at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)`
    `at SSLPoke.main(SSLPoke.java:28)`

I then checked some old notes about some network changes at my job. We would
need in some cases to add the JVM parameter
-Djava.net.preferIPv4Stack=true to make connections to certain machines
in our network to avoid this error.

C:Javajdk1.8.0_111jrelibsecurity>"C:Javajdk1.8.0_111binjava"  
    **-Djava.net.preferIPv4Stack=true**  SSLPoke tfs.corp.****.com 443

Successfully connected

The code for SSLPoke can be downloaded from here:
https://gist.github.com/4ndrej/4547029

answered Oct 27, 2021 at 19:53

JamesKDell's user avatar

This error happened to me while testing my soap service with SoapUI client, basically I was trying to get a very big message (>500kb) and SoapUI closed the connection by timeout.

On SoapUI go to:

File—>Preferences—Socket Timeout(ms)

…and put a large value, such as 180000 (3 minutes), this won’t be the perfect fix for your issue because the file is in fact to large, but at least you will have a response.

answered Sep 22, 2016 at 9:19

Marco's user avatar

MarcoMarco

2,3952 gold badges24 silver badges15 bronze badges

Closed connection in another client

In my case, the error was:

java.net.SocketException: Software caused connection abort: recv failed

It was received in eclipse while debugging a java application accessing a H2 database. The source of the error was that I had initially opened the database with SQuirreL to check manually for integrity. I did use the flag to enable multiple connections to the same DB (i.e. AUTO_SERVER=TRUE), so there was no problem connecting to the DB from java.

The error appeared when, after a while —it is a long java process— I decided to close SQuirreL to free resources. It appears as if SQuirreL were the one «owning» the DB server instance and that it was shut down with the SQuirreL connection.

Restarting the Java application did not yield the error again.

config

  • Windows 7
  • Eclipse Kepler
  • SQuirreL 3.6
  • org.h2.Driver ver 1.4.192

answered Feb 23, 2017 at 12:22

manuelvigarcia's user avatar

manuelvigarciamanuelvigarcia

1,3961 gold badge18 silver badges31 bronze badges

In the situation explained below, client side will throw such an exception:

The server is asked to authenticate client certificate, but the client provides a certificate which Extended Key Usage doesn’t support client auth, so the server doesn’t accept the client’s certificate, and then it closes the connection.

lrnzcig's user avatar

lrnzcig

3,8084 gold badges38 silver badges50 bronze badges

answered Oct 13, 2017 at 1:05

xiaoming's user avatar

xiaomingxiaoming

9997 silver badges10 bronze badges

2

My server was throwing this exception in the pass 2 days and I solved it by moving the disconnecting function with:

outputStream.close();
inputStream.close();
Client.close();

To the end of the listing thread.
if it will helped anyone.

answered Sep 27, 2015 at 12:56

Sefi Erlich's user avatar

In my case, I developped the client and the server side, and I have the exception :

Cause : error marshalling arguments; nested exception is:
java.net.SocketException: Software caused connection abort: socket
write error

when classes in client and server are different. I don’t download server’s classes (Interfaces) on the client, I juste add same files in the project.
But the path must be exactly the same.
For example, on the server project I have javarmiservices packages with some serviceInterface and implementations, I have to create the same package on the client project. If I change it by java/rmi/server/services for example, I get the above exception.
Same exception if the interface version is different between client and server (even with an empty row added inadvertently … I think rmi makes a sort of hash of classes to check version … I don’t know…
If it could help …

answered Dec 20, 2019 at 8:16

Elloco's user avatar

EllocoElloco

2352 silver badges9 bronze badges

I was facing the same problem with wireMock while mocking the rest API calls.
Earlier I was defining the server like this:

WireMockServer wireMockServer = null;

But it should be defined like as shown below:

@Rule 
public WireMockRule wireMockRule = new WireMockRule(8089);

Bojan B's user avatar

Bojan B

2,0734 gold badges18 silver badges26 bronze badges

answered Dec 1, 2016 at 10:35

Yallaling Goudar's user avatar

1

Given this stack trace snippet

Caused by: java.net.SocketException:
Software caused connection abort:
socket write error
 at
java.net.SocketOutputStream.socketWrite0(Native
Method)

I tried to answer the following questions:

  1. What code is throwing this exception? (JVM?/Tomcat?/My code?)
  2. What causes this exception to be thrown?

Regarding #1:

Sun’s JVM source doesn’t contain this exact message, but I think the text Software caused connection abort: socket write error is from the native implementation of SocketOutputStream:

private native void socketWrite0(FileDescriptor fd, byte[] b, int off,
                 int len) throws IOException;

Regarding #2

My guess is that it is caused when the client has terminated the connection, before getting the full response (e.g. sent a request, but before getting the full response, it got closed / terminated / offline)

Questions:

  1. Are the above assumptions correct (#1 and #2)?
  2. Can this be diffrentiated from the situation: «could not write to the client, due to a network error on the server side»? or would that render the same error message?
  3. And most important: Is there an official document (e.g from Sun) stating the above?

I need to have a proof that this stack trace is the socket client’s «fault», and there is nothing that the server could have done to avoid it. (except catching the exception, or using a non Sun JVM SocketOutputStream, though both don’t really avoid the fact the client has terminated)

asked Jan 24, 2010 at 9:52

Eran Medan's user avatar

Eran MedanEran Medan

43.9k61 gold badges182 silver badges275 bronze badges

4

The java.net.SocketException is thrown when there is an error creating or accessing a socket (such as TCP). This usually can be caused when the server has terminated the connection (without properly closing it), so before getting the full response. In most cases this can be caused either by the timeout issue (e.g. the response takes too much time or server is overloaded with the requests), or the client sent the SYN, but it didn’t receive ACK (acknowledgment of the connection termination). For timeout issues, you can consider increasing the timeout value.

The Socket Exception usually comes with the specified detail message about the issue.

Example of detailed messages:

  • Software caused connection abort: recv failed.

    The error indicates an attempt to send the message and the connection has been aborted by your server. If this happened while connecting to the database, this can be related to using not compatible Connector/J JDBC driver.

    Possible solution: Make sure you’ve proper libraries/drivers in your CLASSPATH.

  • Software caused connection abort: connect.

    This can happen when there is a problem to connect to the remote. For example due to virus-checker rejecting the remote mail requests.

    Possible solution: Check Virus scan service whether it’s blocking the port for the outgoing requests for connections.

  • Software caused connection abort: socket write error.

    Possible solution: Make sure you’re writing the correct length of bytes to the stream. So double check what you’re sending. See this thread.

  • Connection reset by peer: socket write error / Connection aborted by peer: socket write error

    The application did not check whether keep-alive connection had been timed out on the server side.

    Possible solution: Ensure that the HttpClient is non-null before reading from the connection.E13222_01

  • Connection reset by peer.

    The connection has been terminated by the peer (server).

  • Connection reset.

    The connection has been either terminated by the client or closed by the server end of the connection due to request with the request.

    See: What’s causing my java.net.SocketException: Connection reset?

Community's user avatar

answered Aug 25, 2016 at 11:11

kenorb's user avatar

kenorbkenorb

149k80 gold badges668 silver badges723 bronze badges

1

I have seen this most often when a corporate firewall on a workstation/laptop gets in the way, it kills the connection.

eg. I have a server process and a client process on the same machine. The server is listening on all interfaces (0.0.0.0) and the client attempts a connection to the public/home interface (note not the loopback interface 127.0.0.1).

If the machine is has its network disconnected (eg wifi turned off) then the connection is formed. If the machine is connected to the corporate network (directly or vpn) then the connection is formed.

However, if the machine is connected to a public wifi (or home network) then the firewall kicks in an kills the connection. In this situation connecting the client to the loopback interface works fine, just not to the home/public interface.

Hope this helps.

akjoshi's user avatar

akjoshi

15.1k13 gold badges104 silver badges120 bronze badges

answered Jan 31, 2013 at 11:46

user2028913's user avatar

1

To prove which component fails I would monitor the TCP/IP communication using wireshark and look who is actaully closing the port, also timeouts could be relevant.

answered Jan 24, 2010 at 11:01

stacker's user avatar

stackerstacker

67.5k27 gold badges140 silver badges209 bronze badges

3

For anyone using simple Client Server programms and getting this error, it is a problem of unclosed (or closed to early) Input or Output Streams.

answered Nov 25, 2014 at 7:33

PRO_gramista's user avatar

PRO_gramistaPRO_gramista

9221 gold badge9 silver badges25 bronze badges

1

Have you checked the Tomcat source code and the JVM source ? That may give you more help.

I think your general thinking is good. I would expect a ConnectException in the scenario that you couldn’t connect. The above looks very like it’s client-driven.

answered Jan 24, 2010 at 9:57

Brian Agnew's user avatar

Brian AgnewBrian Agnew

266k36 gold badges331 silver badges439 bronze badges

7

I was facing the same issue.
Commonly This kind of error occurs due to client has closed its connection and server still trying to write on that client.
So make sure that your client has its connection open until server done with its outputstream.
And one more thing, Don`t forgot to close input and output stream.

Hope this helps.
And if still facing issue than brief your problem here in details.

answered Jun 28, 2016 at 11:41

Nirav Chhatrola's user avatar

1

Had an SSLPoke.bat (SSL troubleshooting script) window script that was getting this error despite importing the correct certificates into the cacerts trustore.

C:Javajdk1.8.0_111jrelibsecurity>SSLPoke.bat

C:Javajdk1.8.0_111jrelibsecurity>"C:jdk1.8.0_101jrebinjava" 
     `SSLPoke  tfs.corp.****.com  443`

java.net.SocketException: Software caused connection abort: recv failed
    `at java.net.SocketInputStream.socketRead0(Native Method)`
    `at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)`
    `at java.net.SocketInputStream.read(SocketInputStream.java:170)`
    `at java.net.SocketInputStream.read(SocketInputStream.java:141)`
    `at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)`
    `at sun.security.ssl.InputRecord.read(InputRecord.java:503)`
    `at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)`
    `at sun.security.ssl.SSLSocketImpl.performInitialHandshake
       (SSLSocketImpl.java:1375)`
    `at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)`
    `at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)`
    `at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)`
    `at SSLPoke.main(SSLPoke.java:28)`

I then checked some old notes about some network changes at my job. We would
need in some cases to add the JVM parameter
-Djava.net.preferIPv4Stack=true to make connections to certain machines
in our network to avoid this error.

C:Javajdk1.8.0_111jrelibsecurity>"C:Javajdk1.8.0_111binjava"  
    **-Djava.net.preferIPv4Stack=true**  SSLPoke tfs.corp.****.com 443

Successfully connected

The code for SSLPoke can be downloaded from here:
https://gist.github.com/4ndrej/4547029

answered Oct 27, 2021 at 19:53

JamesKDell's user avatar

This error happened to me while testing my soap service with SoapUI client, basically I was trying to get a very big message (>500kb) and SoapUI closed the connection by timeout.

On SoapUI go to:

File—>Preferences—Socket Timeout(ms)

…and put a large value, such as 180000 (3 minutes), this won’t be the perfect fix for your issue because the file is in fact to large, but at least you will have a response.

answered Sep 22, 2016 at 9:19

Marco's user avatar

MarcoMarco

2,3952 gold badges24 silver badges15 bronze badges

Closed connection in another client

In my case, the error was:

java.net.SocketException: Software caused connection abort: recv failed

It was received in eclipse while debugging a java application accessing a H2 database. The source of the error was that I had initially opened the database with SQuirreL to check manually for integrity. I did use the flag to enable multiple connections to the same DB (i.e. AUTO_SERVER=TRUE), so there was no problem connecting to the DB from java.

The error appeared when, after a while —it is a long java process— I decided to close SQuirreL to free resources. It appears as if SQuirreL were the one «owning» the DB server instance and that it was shut down with the SQuirreL connection.

Restarting the Java application did not yield the error again.

config

  • Windows 7
  • Eclipse Kepler
  • SQuirreL 3.6
  • org.h2.Driver ver 1.4.192

answered Feb 23, 2017 at 12:22

manuelvigarcia's user avatar

manuelvigarciamanuelvigarcia

1,3961 gold badge18 silver badges31 bronze badges

In the situation explained below, client side will throw such an exception:

The server is asked to authenticate client certificate, but the client provides a certificate which Extended Key Usage doesn’t support client auth, so the server doesn’t accept the client’s certificate, and then it closes the connection.

lrnzcig's user avatar

lrnzcig

3,8084 gold badges38 silver badges50 bronze badges

answered Oct 13, 2017 at 1:05

xiaoming's user avatar

xiaomingxiaoming

9997 silver badges10 bronze badges

2

My server was throwing this exception in the pass 2 days and I solved it by moving the disconnecting function with:

outputStream.close();
inputStream.close();
Client.close();

To the end of the listing thread.
if it will helped anyone.

answered Sep 27, 2015 at 12:56

Sefi Erlich's user avatar

In my case, I developped the client and the server side, and I have the exception :

Cause : error marshalling arguments; nested exception is:
java.net.SocketException: Software caused connection abort: socket
write error

when classes in client and server are different. I don’t download server’s classes (Interfaces) on the client, I juste add same files in the project.
But the path must be exactly the same.
For example, on the server project I have javarmiservices packages with some serviceInterface and implementations, I have to create the same package on the client project. If I change it by java/rmi/server/services for example, I get the above exception.
Same exception if the interface version is different between client and server (even with an empty row added inadvertently … I think rmi makes a sort of hash of classes to check version … I don’t know…
If it could help …

answered Dec 20, 2019 at 8:16

Elloco's user avatar

EllocoElloco

2352 silver badges9 bronze badges

I was facing the same problem with wireMock while mocking the rest API calls.
Earlier I was defining the server like this:

WireMockServer wireMockServer = null;

But it should be defined like as shown below:

@Rule 
public WireMockRule wireMockRule = new WireMockRule(8089);

Bojan B's user avatar

Bojan B

2,0734 gold badges18 silver badges26 bronze badges

answered Dec 1, 2016 at 10:35

Yallaling Goudar's user avatar

1

I am trying to send an image from a Java desktop application to a J2ME application. The problem is that I am getting this exception:

java.net.SocketException: Software caused connection abort: socket write error

I have looked around on the net, and although this problem is not that rare, I was unable to find a concrete solution. I am transforming the image into a byte array before transferring it. These are the methods found on the desktop application and on the J2ME respectively

    public void send(String ID, byte[] serverMessage) throws Exception
    {            
        //Get the IP and Port of the person to which the message is to be sent.
        String[] connectionDetails = this.userDetails.get(ID).split(",");
        Socket sock = new Socket(InetAddress.getByName(connectionDetails[0]), Integer.parseInt(connectionDetails[1]));
        OutputStream os = sock.getOutputStream();
        for (int i = 0; i < serverMessage.length; i++)
        {
            os.write((int) serverMessage[i]);
        }
        os.flush();
        os.close();
        sock.close();
    }

    private void read(final StreamConnection slaveSock)
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                try
                {
                    DataInputStream dataInputStream = slaveSock.openDataInputStream();
                    int inputChar;
                    StringBuffer results = new StringBuffer();
                    while ( (inputChar = dataInputStream.read()) != -1)
                    {
                        results.append((char) inputChar);
                    }
                    dataInputStream.close();
                    slaveSock.close();
                    parseMessage(results.toString());
                    results = null;
                }

                catch(Exception e)
                {
                    e.printStackTrace();
                    Alert alertMsg = new Alert("Error", "An error has occured while reading a message from the server:n" + e.getMessage(), null, AlertType.ERROR);
                    alertMsg.setTimeout(Alert.FOREVER);
                    myDisplay.setCurrent(alertMsg, resultScreen);
                }
            }
        };
        new Thread(runnable).start();
    }   

I am sending the message across a LAN, and I have no problems when I send short text messages instead of images. Also, I used wireshark and it seems that the desktop application is only sending part of the message. Any help would be highly appreciated. Also, everything works on the J2ME simulator.

Содержание

  1. Software caused connection abort: socket write error
  2. Comments
  3. How to fix java.net.SocketException: Software caused connection abort: recv failed
  4. Scenario 1: java.net.SocketException: Software caused connection abort: recv failed
  5. Scenario 1: java.net.SocketException: Software caused connection abort: recv failed
  6. java.net.SocketException: Software caused connection abort: socket write er
  7. Официальные причины » программное обеспечение вызвало прерывание соединения: ошибка записи сокета»
  8. 12 ответов:
  9. закрытое соединение в другом клиенте

Software caused connection abort: socket write error

I have that «Software caused connection abort: socket write error» exception error that i’ve never meet before.
When I try without using SSLSocket, I have the same «Software caused connection abort: socket write error»
What does it means ?
What is going wrong with my code?

Here is the code I wrote :
//server side //client side and the server log error : Edited by: kuguy on Mar 6, 2008 1:49 AM

Also you must use the same ObjectOutputStream and ObjectInputStream for the life of the socket.

Thanks for the thread link.. interesting description..
so is there any way to solve this issues.
if you look at the code, basically what im trying to do is the following:
— a client connect to a server using sslsocket.
— server receive the connection and reply with the first part of the data and keep the connection open.
— then client receive the reply and request for another data using the same socket connection
— then server receive the next request and reply with the second part of the data and close the connection when the loop is finish.

what im trying to do is actually to chunk the download size. consider I need to download a 20MB of data from the server, using a single request is fine, but client have to wait for sometime until all the data is downloaded. so im trying to chunk the data into several part, and the server will send the chunk of data one by one. so the moment client receive the first part of the data, it will display it directly and at the same time will process the next data.

creating a new socket request for each chunk of data will be slow since it has to keep open and close the socket to server several times.

so in short, im trying to utilize one socket connection to do several data communication between client and server.
can you help point out what i did wrong in doing this. or a link to any site providing example in doing this.

Thanking you in advance for your help and sorry for the length of the post..

Источник

How to fix java.net.SocketException: Software caused connection abort: recv failed

Out of many client servers related socket errors here is one more interesting socket related error from the Java program, «java.net.SocketException: Software caused connection abort: recv failed». The key point in this error message is «abort» and «recv», which means is someone (client or server) is trying to read from a closed connection. This error usually comes at the client socket end, when the server closed the connection before the client has read the response, but, in general, it can come to an end of the TCP socket, so you must check the log files for both clients and server to find out who is complaining. If the Server is complaining then it’s fine and the client has closed the TCP connection may be due to timeout or any RuntimeException at the client end.

If the client’s log file contains this error it means your client is fine and it’s the server who is closing the connection prematurely. This generally happens when the Server is waiting for the response from some other process e.g. another and that is overloaded and in the meantime, the client request has timed out at the Server end.

Many Java developers encounter «java.net.SocketException: Software caused connection abort: recv failed» error at different places e.g. it can come when your Java program is connected to MySQL database and left running idle for many hours. You may get this while using products written in Java like Tomcat, Apache Cassandra or Apache Axis 2. It can also be related to database problems. Just check if Server is healthy and why it’s closing the connection.

Scenario 1: java.net.SocketException: Software caused connection abort: recv failed

If you are using a client-server application then doing following will reproduce the problem:

  1. Client sends a request req#1
  2. Server reads the first request req#1, processes, writes a response
  3. Server closes connection
  4. Client sends second request req#2
  5. Client tries to read server response: «java.net.SocketException: Software caused connection abort: recv failed» as shown below:

java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(SocketInputStream.java:0)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.net.SocketInputStream.read(SocketInputStream.java:182)

Solution 1:
Check why your client is sending the second request before reading the response of the first request. Look for any multi-threading angle if the error is intermittent.

Scenario 1: java.net.SocketException: Software caused connection abort: recv failed

I have also seen this error while working with a Java Web application connecting to a database. When you left your application overnight and there is no request to process during the night, in the morning it was throwing «java.sql.SQLException: Communication link failure: java.net.SocketException, underlying cause: Software caused connection abort: recv failed» error.

The real cause of the problem was that the database timed out the connection when left idle and when the Java application tries to connect to the database using those stale connections it throws java.sql.SQLException: Communication link failure: java.net.SocketException, underlying cause: Software caused connection abort: recv failed error.

Solution 2:
Since we were using the c3po connection pool from Hibernate and enabled connection.autoReconnect , connection.autoReconnectForPools , and connection.is-connection-validation-required set, I was wondering why this issue is coming even if we auto-connect enabled. The real reason was that we have not provided the validationQuery property and JDBC drivers need validation queries to test the connection during the idle period.

You can use queries like «SELECT 1» or «SELECT 1 from DUAL» depending upon which database you are connecting In our case, it was Microsoft SQL SERVER 2008 but this error can happen with any database e.g MySQL or Oracle. Use the second validation query if you are connecting to the Oracle database from Java application using the c3p0 connection pool.

Источник

java.net.SocketException: Software caused connection abort: socket write er

hello,
i m doing project on jmf. my project is video conferncing. i m using weblogic8.0,
jdk1.4,jsp,applet,webcam by adcom and head phone. but when i m running in localhost in my desktop pc it is showing the exception mentionas : java.net.SocketException: Software caused connection abort: socket write error

and the jsp file showing error as: content type error multipart/form-data io exception. so, anybody know this.. pls help me. exam knocking .
very urgenttttttttttttttttttt i m sending the thread socket code..
//This is the thread module to upload movie files on the server from applet to the jsp file
import java.io.*;
import java.net.Socket;
import java.net.URL;

public class UploadThread extends Thread <
private StringBuffer sb = new StringBuffer(); // Server Output.
private Exception e = null; // Thread Exception.
private static int TIME_EACH_CLIP = 10000; // in miliseconds
private String uploadURL = «http://localhost:7001/Project/parserUpload.jsp»; //Default Value
private String file = «test»; //Default Value

public void setFile(String fname) <
this.file = fname;
>

public void setuploadURL(String url) <
this.uploadURL = url;
>

// Server Output.
public StringBuffer getServerOutput() <
return sb;
>

// Exceptions
public Exception getException() <
return e;
>

Источник

Официальные причины » программное обеспечение вызвало прерывание соединения: ошибка записи сокета»

учитывая этот фрагмент трассировки стека

вызвано: java. net. SocketException:
Программное обеспечение вызвало разрыв соединения :
ошибка записи сокета
at
Ява.чистая.SocketOutputStream.socketWrite0(родной
Метод)

Я попытался ответить на следующие вопросы:

  1. какой код бросает это исключение? (JVM?- Кот?-Мой код?)
  2. что вызывает это исключение бросили?

О #1:

источник Sun JVM не содержит этого точного сообщения, но я думаю, что текст программное обеспечение вызвало прерывание соединения: ошибка записи сокета из родной реализации SocketOutputStream :

о #2

Я предполагаю, что это вызвано тем, что клиент прекратил соединение, прежде чем получить полный ответ (например, отправил запрос, но до получения полный ответ, он был закрыт / прекращен / отключен)

вопросы:

  1. верны ли приведенные выше предположения (#1 и #2)?
  2. можно ли это отличить от ситуации: «не удалось написать клиенту из-за ошибки сети на сервер стороне»? или это будет отображать одно и то же сообщение об ошибке?
  3. и самое главное: есть ли официальный документ (например, от Sun), в котором говорится наверху?

мне нужно иметь доказательство того, что эта трассировка стека является «ошибкой» клиента сокета, и нет ничего, что сервер мог бы сделать, чтобы избежать этого. (за исключением перехвата исключения или использования не Sun JVM SocketOutputStream, хотя оба они на самом деле не избегают того факта, что клиент прекратил работу)

12 ответов:

» эта ошибка может возникать, когда локальная сетевая система прерывает соединение, например, когда WinSock закрывает установленное соединение после сбоя повторной передачи данных (приемник никогда не подтверждает данные, отправленные на сокет потока данных).». Смотрите этой статье. Смотрите также некоторые сведения о «программное обеспечение вызвало прерывание соединения».

Я видел это чаще всего, когда корпоративный брандмауэр на рабочей станции/ноутбука встает на пути, он убивает соединение.

например. У меня есть серверный процесс и клиентский процесс на одном компьютере. Сервер прослушивает все интерфейсы (0.0.0.0), и клиент пытается подключиться к общедоступному/домашнему интерфейсу (обратите внимание, что не интерфейс замыкания на себя 127.0.0.1).

Если машина имеет свою сеть отключена (например, Wi-Fi выключен), то соединение формируется. Если машина подключается к корпоративной сети (напрямую или vpn), после чего формируется соединение.

однако, если машина подключена к общественной Wi-Fi (или домашней сети), то брандмауэр пинает в убивает соединение. В этой ситуации подключение клиента к интерфейсу обратной связи работает нормально, только не к домашнему/общедоступному интерфейсу.

надеюсь, что это помогает.

чтобы доказать, какой компонент не работает, я бы контролировал связь TCP / IP с помощью wireshark и посмотрите, кто actaully закрывает порт, также тайм-ауты могут быть актуальными.

на java.net.SocketException бросается, когда есть ошибка создания или доступа сокет (например, TCP). Это обычно может быть вызвано, когда сервер прекратил соединение (без надлежащего закрытия его), поэтому перед получением полного ответа. В большинстве случаев это может быть вызвано либо проблемой таймаута (например, ответ занимает слишком много времени или сервер перегружен запросами), либо клиент отправил SYN, но он не получил ACK (подтверждение прекращения соединения). Для проблем с таймаутом можно рассмотреть возможность увеличения значения таймаута.

исключение сокета обычно поставляется с указанным подробным сообщением о проблеме.

пример подробных сообщений:

программное обеспечение вызвало прерывание соединения: recv не удалось.

ошибка указывает на попытку отправить сообщение и соединение было прервано сервером. Если это произошло при подключении к базе данных, это может быть связано с использованием не совместимый разъем / J драйвер JDBC.

возможное решение: убедитесь, что у вас есть правильные библиотеки/драйверы в вашем пути к классам.

программное обеспечение вызвало разрыв соединения: подключение.

Это может произойти, когда есть проблема, чтобы подключиться к удаленному. Например из-за вирусной проверки, отклоняющей удаленную почту запросы.

возможное решение: проверьте службу проверки на вирусы, блокирует ли она порт для исходящих запросов на соединения.

программное обеспечение вызвало прерывание соединения: ошибка записи сокета.

возможное решение: убедитесь, что вы записываете правильную длину байтов в поток. Так что дважды проверьте, что вы отправляете. Смотрите это thread.

подключение сброс одноранговым узлом: ошибка записи сокета / Соединение прервано одноранговым узлом: ошибка записи сокета

приложение не проверило, было ли время ожидания соединения keep-alive на стороне сервера.

возможное решение: убедитесь, что HttpClient не является нулевым перед чтением из соединения. E13222_01

подключение завершается одноранговым узлом (сервером).

соединение было либо прекращено клиентом, либо закрыто серверным концом соединения из-за запроса с запросом.

вы проверили исходный код Tomcat и источник JVM ? Это может дать вам больше помощи.

Я думаю, что ваше общее мышление-это хорошо. Я ожидал бы ConnectException в сценарии, который вы не смогли подключиться. Это выглядит очень похоже на это клиента.

для тех, кто использует простые клиент-серверные программы и получает эту ошибку, это проблема незамкнутых (или закрытых для ранних) входных или выходных потоков.

Я столкнулся с той же проблемой.
Обычно такая ошибка возникает из-за того, что клиент закрыл свое соединение, а сервер все еще пытается писать на этом клиенте.
Поэтому убедитесь, что ваш клиент имеет свое соединение открыто, пока сервер не закончит с его outputstream.
И еще одно, Не забудьте закрыть входной и выходной поток.

надеюсь, что это помогает.
И если все еще сталкивается с проблемой, чем кратко вашу проблему здесь в деталях.

эта ошибка произошла со мной во время тестирования моего soap-сервиса с клиентом SoapUI, в основном я пытался получить очень большое сообщение (>500kb), и SoapUI закрыл соединение по таймауту.

File— > Preferences—Socket Timeout (ms)

. и поставьте большое значение, например 180000 (3 минуты), это не будет идеальным решением для вашей проблемы, потому что файл на самом деле большой, но по крайней мере у вас будет ответ.

закрытое соединение в другом клиенте

в моем случае, ошибка была:

Он был получен в eclipse при отладке приложения java, обращающегося к базе данных H2. Источником ошибки было то, что я изначально открыл базу данных с Белкой, чтобы вручную проверить целостность. Я использовал флаг для включения нескольких подключений к одной и той же БД (т. е. AUTO_SERVER=TRUE ), поэтому не было никаких проблем с подключением к БД с java.

ошибка появилась когда через некоторое время-это долгий процесс java-я решил закрыть белку для свободных ресурсов. Похоже, что SQuirreL был тем, кто «владел» экземпляром сервера БД, и что он был закрыт с помощью соединения SQuirreL.

перезапуск приложения Java не привел к повторной ошибке.

config

  • Windows 7
  • Затмение Кеплер
  • белка 3.6
  • org.h2.Водитель ver 1.4.192

мой сервер бросал это исключение в течение 2 дней, и я решил его, переместив функцию отключения с помощью:

до конца потока листинга. если это кому-то поможет.

в ситуации, описанной ниже, клиентская сторона выдаст такое исключение:

серверу предлагается аутентифицировать сертификат клиента, но клиент предоставляет сертификат, который расширенное использование ключа не поддерживает аутентификацию клиента, поэтому сервер не принимает сертификат клиента, а затем закрывает соединение.

я столкнулся с той же проблемой с wireMock, издеваясь над вызовами REST API. Ранее я определял сервер следующим образом:

но он должен быть определен, как показано ниже:

Источник

Hi all,

I have that «Software caused connection abort: socket write error» exception error that i’ve never meet before.
When I try without using SSLSocket, I have the same «Software caused connection abort: socket write error»
What does it means ?
What is going wrong with my code?

Here is the code I wrote :
//server side

GZIPOutputStream gos = new GZIPOutputStream(child.getOutputStream());
GZIPInputStream gis = new GZIPInputStream(child.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(gos,48000));
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(gis,48000));

out.writeObject( passRequest( obj ) );
out.flush();
gos.finish();
String sDate, eDate;

do{ 
  gis = new GZIPInputStream(child.getInputStream()); 
  in = new ObjectInputStream(new BufferedInputStream(gis,48000));
  obj=in.readObject();

  Vector<String> dates = (Vector<String>) ((CRequest) obj)
  .getInfo();
  String start = dates.get(0);
  String end = dates.get(1);  
  SimpleDateFormat sdf = new SimpleDateFormat(
      "MMM dd, yyyy hh:mm:ss a"); 
  SimpleDateFormat sdf3 = new SimpleDateFormat(
      "yyyy-MM-dd HH:mm:ss");

  Date startD = null;
  Date endD = null;

  try {
    startD = sdf.parse(start);
    endD = sdf.parse(end);
  } catch (ParseException e1) {

    e1.printStackTrace();
  }
  sDate = sdf3.format(startD);
  eDate = sdf3.format(endD); 
  gos = new GZIPOutputStream(child.getOutputStream()); 
  out = new ObjectOutputStream(new BufferedOutputStream(gos,48000)); 
  out.writeObject( passRequest( obj ) ); 
  out.flush();
  gos.finish(); 
  
}while(!sDate.equals(eDate));

//client side

sslFact = (SSLSocketFactory) SSLSocketFactory
.getDefault();
server = (SSLSocket) sslFact.createSocket(ip, port);
server.setEnabledCipherSuites(set);
server.setReceiveBufferSize(48000);
server.setSendBufferSize(48000);
          
Date currentEnd = GlobalMethods.sDate; 
Date currentStart;
long period = 1000*60*60*6; //6 hours
long endTime = GlobalMethods.eDate.getTime();

//request splitted historical time until end date is reached
//if currentStart and currentEnd are equals, so it's the last request 
while(currentEnd.getTime() < endTime){
  
  currentStart = currentEnd; 
  long nextPeriod = currentStart.getTime() + period;
  if(nextPeriod < endTime)
    currentEnd = new Date(nextPeriod);
  else
    currentEnd = new Date(endTime);

  dates.clear();
  dates.add(currentStart.toLocaleString());
  dates.add(currentEnd.toLocaleString()); 

  creq = new CRequest(Activator.cookie,
      RequestConstants.CMC_REQUEST_DATA, segment, dates,
      ip, port);  
  gos = new GZIPOutputStream(server.getOutputStream());
  out = new ObjectOutputStream(new BufferedOutputStream(gos, 48000));  
  // /* Can we actually send ourselves and then receive ourselves?*/
  out.writeObject(creq); 
  out.flush();
  gos.finish(); 
  gis = new GZIPInputStream(server.getInputStream()); 
  in = new ObjectInputStream(new BufferedInputStream(gis, 48000)); 
  /* Returning the newly modified request with results */
  final CRequest received = (CRequest) in.readObject();  

  PlatformUI.getWorkbench().getDisplay().asyncExec(
      new Runnable() {
        public void run() { 
          pref.processData((GeneralDataObj) received
              .getInfo());
        }
      }); 
}

and the server log error :

javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLException: 

java.net.SocketException: Software caused connection abort: socket write error
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkEOF(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkWrite(Unknown Source)
	at com.sun.net.ssl.internal.ssl.AppOutputStream.write(Unknown Source)
	at java.util.zip.DeflaterOutputStream.deflate(Unknown Source)
	at java.util.zip.DeflaterOutputStream.write(Unknown Source)
	at java.util.zip.GZIPOutputStream.write(Unknown Source)
	at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
	at java.io.BufferedOutputStream.write(Unknown Source)
	at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
	at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown 

Source)
	at java.io.ObjectOutputStream.writeNonProxyDesc(Unknown Source)
	at java.io.ObjectOutputStream.writeClassDesc(Unknown Source)
	at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	at java.io.ObjectOutputStream.writeFatalException(Unknown Source)
	at java.io.ObjectOutputStream.writeObject(Unknown Source)
	at com.inetmon.jn.server.SessionManager.run(SessionManager.java:153)
Caused by: javax.net.ssl.SSLException: java.net.SocketException: Software caused 

connection abort: socket write error
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(Unknown Source)
	at com.sun.net.ssl.internal.ssl.AppOutputStream.write(Unknown Source)
	at java.util.zip.DeflaterOutputStream.deflate(Unknown Source)
	at java.util.zip.DeflaterOutputStream.write(Unknown Source)
	at java.util.zip.GZIPOutputStream.write(Unknown Source)
	at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
	at java.io.BufferedOutputStream.write(Unknown Source)
	at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
	at java.io.ObjectOutputStream$BlockDataOutputStream.write(Unknown Source)
	at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
	at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
	at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	at java.io.ObjectOutputStream.writeArray(Unknown Source)
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
	at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
	at java.util.Vector.writeObject(Unknown Source)
	at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
	at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
	at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
	at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
	at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
	at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
	at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
	at java.io.ObjectOutputStream.writeObject0(Unknown Source)
	... 2 more
Caused by: java.net.SocketException: Software caused connection abort: socket write error
	at java.net.SocketOutputStream.socketWrite0(Native Method)
	at java.net.SocketOutputStream.socketWrite(Unknown Source)
	at java.net.SocketOutputStream.write(Unknown Source)
	at com.sun.net.ssl.internal.ssl.OutputRecord.writeBuffer(Unknown Source)
	at com.sun.net.ssl.internal.ssl.OutputRecord.write(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(Unknown Source)
	... 34 more

Edited by: kuguy on Mar 6, 2008 1:49 AM

Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

Out of many client servers related socket errors here is one more interesting socket related error from the Java program, «java.net.SocketException: Software caused connection abort: recv failed». The key point in this error message is «abort» and «recv», which means is someone (client or server) is trying to read from a closed connection. This error usually comes at the client socket end, when the server closed the connection before the client has read the response, but, in general, it can come to an end of the TCP socket, so you must check the log files for both clients and server to find out who is complaining. If the Server is complaining then it’s fine and the client has closed the TCP connection may be due to timeout or any RuntimeException at the client end.

If the client’s log file contains this error it means your client is fine and it’s the server who is closing the connection prematurely. This generally happens when the Server is waiting for the response from some other process e.g. another and that is overloaded and in the meantime, the client request has timed out at the Server end.

Many Java developers encounter «java.net.SocketException: Software caused connection abort: recv failed» error at different places e.g. it can come when your Java program is connected to MySQL database and left running idle for many hours. You may get this while using products written in Java like Tomcat, Apache Cassandra or Apache Axis 2. It can also be related to database problems. Just check if Server is healthy and why it’s closing the connection.

Scenario 1:  java.net.SocketException: Software caused connection abort: recv failed

If you are using a client-server application then doing following will reproduce the problem:

  1. Client sends a request req#1
  2. Server reads the first request req#1, processes, writes a response
  3. Server closes connection
  4. Client sends second request req#2
  5. Client tries to read server response: «java.net.SocketException: Software caused connection abort: recv failed» as shown below:

java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(SocketInputStream.java:0)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.net.SocketInputStream.read(SocketInputStream.java:182)

Solution 1:
Check why your client is sending the second request before reading the response of the first request. Look for any multi-threading angle if the error is intermittent.

How to solve java.net.SocketException: Software caused connection abort: recv failed

Scenario 1:  java.net.SocketException: Software caused connection abort: recv failed

I have also seen this error while working with a Java Web application connecting to a database. When you left your application overnight and there is no request to process during the night, in the morning it was throwing «java.sql.SQLException: Communication link failure: java.net.SocketException, underlying cause: Software caused connection abort: recv failed» error.

The real cause of the problem was that the database timed out the connection when left idle and when the Java application tries to connect to the database using those stale connections it throws java.sql.SQLException: Communication link failure: java.net.SocketException, underlying cause: Software caused connection abort: recv failed error.

Solution 2:
Since we were using the c3po connection pool from Hibernate and enabled connection.autoReconnectconnection.autoReconnectForPools, and connection.is-connection-validation-required set, I was wondering why this issue is coming even if we auto-connect enabled.  The real reason was that we have not provided the validationQuery property and JDBC drivers need validation queries to test the connection during the idle period.

You can use queries like «SELECT 1» or «SELECT 1 from DUAL» depending upon which database you are connecting In our case, it was Microsoft SQL SERVER 2008 but this error can happen with any database e.g MySQL or Oracle. Use the second validation query if you are connecting to the Oracle database from Java application using the c3p0 connection pool.

If you are not using c3p0 but using Apache DBCP connection pool i.e. using org.apache.commons.dbcp.BasicDataSource  in your Spring config file then uses relevant property so that the JDBC connection pool can automatically test the pooled database connection.

That’s all about java.net.SocketException: Software caused connection abort: recv failed». You see the root cause is that one party, usually the server has closed the connection but the client is trying to read from that connection. I understand every situation is different and it may require different solutions but knowing this fundamental will help you to quickly troubleshoot your issue.

Other Java troubleshooting Guides

  • java.net.SocketException: Failed to read from SocketChannel: Connection reset by peer [fix]
  • java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet [fix]
  • 2 ways to solve Unsupported major.minor version 51.0 error in Java [solutions]
  • How to solve java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver [solution]
  • java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver [solution] 
  • How to solve java.lang.UnsatisfiedLinkError: no ocijdbc11 in Java [solution]
  • java.lang.ClassNotFoundException: org.postgresql.Driver [fix]
  • Fixing Unsupported major.minor version 52.0 Error in Java [solution]
  • java.io.IOException: Map failed and java.lang.OutOfMemoryError: Map failed  [fix]
  • Exception in thread «main» java.lang.ExceptionInInitializerError in Java Program [fix]
  • Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: 1 [solution]
  • org.hibernate.MappingException: Unknown entity Exception in Java [solution]
  • java.net.BindException: Cannot assign requested address: JVM_Bind [fix]
  • java.net.SocketException: Too many files open java.io.IOException [solution]

I have a TCP Client which continuously sends data to the server(The server is running continuously). It creates connection each time to the server to send the data. However, it throws exception after sending some amount of data to the server. Data is coming from some sensors continuously and that data is sent by my TCP Client to the server.

Here is my piece of TCPClient code :

try {

System.out.println(«»Inside Client :»» + device_data);
logger.info(«»Inside Client :»» + device_data);

InputStream is = new ByteArrayInputStream(device_data.getBytes());
BufferedReader socketRead = new BufferedReader(new InputStreamReader(is));

/**
* sending the contents to server. Uses PrintWriter
*/
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);

String str;

/**
* Reading data line by line
*/
while ((str = socketRead.readLine()) != null) {

if(!pwrite.checkError()){
pwrite.println(«»Data sent by Client : «» + str);
logger.info(«»Data sent by client»» + str);
System.out.println(«»Data sent by client»» + str);
}

else{

logger.info(«»Error in writing data»»);
System.out.println(«»Error in writing data»»);
}

}
pwrite.close();
socketRead.close();

}

catch (Exception exception) {

System.out.println(«»Exception»» + exception);
logger.info(«»Exception in TCPClient :»» + exception);
}

Thanks in advance.

Read these next…

  • Curated Snap! -- No-Password Logins, Solar Powered Water Filter, Glitch in the Matrix?

    Snap! — No-Password Logins, Solar Powered Water Filter, Glitch in the Matrix?

    Spiceworks Originals

    Your daily dose of tech news, in brief.

    Welcome to the Snap!

    Flashback: February 9, 1996: Introduction of the Bandai Pippin (Read more HERE.)

    Bonus Flashback: February 9, 1990: Galileo Probe does a Venus Flyby (Read more HERE.)

    You nee…

  • Curated Roku TV being used as Wallboard Issues

    Roku TV being used as Wallboard Issues

    Hardware

    Helping someone out at their shop. They have 4 large Roku screens and 2 laptops with dual HDMI ports for video. They are viewing static website business dashboards and PowerPoint. At first all 4 screens connected to wireless, worked for a while but with a…

  • Curated Charging for SSO

    Charging for SSO

    Security

    We have SSO set up with around 5 or 6 solution providers via our M365. Not one of them charges for this, they just sent us the documentation.I identified another online service in use by one of our departments which would benefit from using SSO for staff …

  • Curated Spark! Pro series - 9th February 2023

    Spark! Pro series — 9th February 2023

    Spiceworks Originals

    Today in History: America meets the Beatles on “The Ed Sullivan Show”

    At approximately 8:12 p.m. Eastern time, Sunday, February 9, 1964, The Ed Sullivan Show returned from a commercial (for Anacin pain reliever), and there was Ed Sullivan standing …

  • Curated Green Brand Rep Wrap-Up: January 2023

    Green Brand Rep Wrap-Up: January 2023

    Spiceworks Originals

    Source Opens a new window Opens a new windowHi, y’all — Chad here. A while back, we used to feature the top posts from our brand reps (aka “Green Gals/Guys/et. al.) in a weekly or monthly wrap-up post. I can’t specifically recall which, as that was ap…


posted 14 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

I have TCP/IP based service which is continously 24*7 running on a port.
It communicates using XML.
when response is < 1023 characters…the client recieves data properly….
but when response is > 1023 characters the client recieves half the response (i.e exactly 1023 chars) and remaining chars are lost…and at the service end it throws exception:
Software caused connection abort: socket write error

Complete stack trace:
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)

at sun.nio.cs.StreamEncoder$CharsetSE.implWrite(StreamEncoder.java:395)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:136)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:191)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
at java.io.BufferedWriter.write(BufferedWriter.java:212)
at java.io.Writer.write(Writer.java:126)
at com.icici.cardvalidator.queryserver.TCPXMLThread.run(TCPXMLThread.jav
a:328)
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)

at sun.nio.cs.StreamEncoder$CharsetSE.implWrite(StreamEncoder.java:395)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:136)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:191)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
at java.io.BufferedWriter.write(BufferedWriter.java:212)
at java.io.Writer.write(Writer.java:126)
at com.icici.cardvalidator.queryserver.TCPXMLThread.run(TCPXMLThread.jav
a:328)

I running JSP on Oracle 11g, Weblogic 10.3.4. I have 2 managed server and a oracle admin server installed.

I am encountering an error where intermittently the log file of the 2 managed server and admin server will show java.net.SocketException: Software caused connection abort: socket write error. The application can run for 2 days without showing this error or it can show up a few times in a day. The server load are similar everday.

When this error is been encountered, the server will just stop accepting connections and will not be able to access the application. Even if I try to access the application through localhost, I will not be able to access the JSP pages and a 503 http status is shown but then I am able to access the static HTML page. I will not be able to access the Oracle 11g Weblogic admin console page. When I take a look at admin server log, it shows that the managed servers are disconnected from the admin server and vice versa.

Magically the application is able to recover by its own and the application is able to access again or I need to restart the server as restarting the service of the application does not work.

The FTP connections that the application is connected to are closed as well.

I am able to ping to telnet to the server port. The event log doesn’t seem to be leaving any information. We did run wireshark to see the packet traffic and it seems that the application port is sending a RST, ACK packet to the load balancer.

Any kind help will greatly be appreciated. Should you need more info, feel free to ask me.

Exception Trace

A-000000> <[Error] GetPageContentTag: pageContext flush error, exception in doEndTag {java.net.SocketException: Software caused connection abort: socket write error}>

Понравилась статья? Поделить с друзьями:
  • Java net socketexception network is unreachable как исправить
  • Java net socketexception connection reset by peer socket write error
  • Java lang unsatisfiedlinkerror как исправить андроид
  • Java lang stackoverflowerror как исправить
  • Java lang securityexception ошибка как исправить на андроид