Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while reading inputstream : Software caused connection abort' in java server

I am basically trying to host a server on an Android Device. Client devices connect to the server over TCP and send requests. The server performs the action requested by the client and then writes data back to the socket. The connection is not terminated by the server and requests are to be continuously read over the socket and replied to.

Note: The first 4 bytes of each request message contain the length of the actual message/request.

The parseXmlInputAndExecuteCmd function executes various asynchronous operations depending on the content of the input XML string. This eventually causes a change in the boolean value of 'allowResponse' variable to true and a certain response is generated which is stored in the variable of type String called 'response'. Once the boolean 'allowResponse' becomes true, the thread resumes execution and writes the response back to the socket's OutputStream

Some of these asynchronous operations include connecting and disconnecting from the corporate VPN. Could that be a cause of the error ?

Some Class level variables being used are :

private volatile boolean allowResponse = false;
private String response;

Server Code:

    private void startServer() {
    try {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket connectionSocket = serverSocket.accept();
            BufferedInputStream bufInpStream = new BufferedInputStream(connectionSocket.getInputStream());
            BufferedOutputStream bufOutStream = new BufferedOutputStream(connectionSocket.getOutputStream());
            ByteArrayOutputStream contentLengthBaos = new ByteArrayOutputStream();
            int c;
            int count = 0;
            while ((c = bufInpStream.read()) != -1) {
                contentLengthBaos.write(c);
                count++;
                if (count == 4) {
                    int contLen = getMessageLength(contentLengthBaos);
                    String content = getMessageContent(bufInpStream, contLen);
                    parseXmlInputAndExecuteCmd(content);
                    count = 0;
                    while (!allowResponse) {
                        Thread.sleep(1000);
                    }
                    allowResponse = false;
                    byte[] responseDataBytes = response.getBytes();
                    int outputContLen = responseDataBytes.length;
                    byte[] contLengthBytes = ByteBuffer.allocate(4).putInt(outputContLen).array();
                    ByteArrayOutputStream o = new ByteArrayOutputStream();
                    o.write(contLengthBytes);
                    o.write(responseDataBytes);
                    byte finalOutPutBytes[] = o.toByteArray();
                    bufOutStream.write(finalOutPutBytes);
                    bufOutStream.flush();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

@NonNull
private String getMessageContent(BufferedInputStream inFromClient, int contLen) throws IOException {
    ByteArrayOutputStream contentBaos = new ByteArrayOutputStream();
    byte[] contentBytes = new byte[contLen];
    for (int i = 0; i < contLen; i++) {
        contentBaos.write(inFromClient.read());
        ByteArrayInputStream bais = new ByteArrayInputStream(contentBaos.toByteArray());
        bais.read(contentBytes);
    }
    String content = new String(contentBytes);
    Log.d(TAG, "Content : " + content);
    return content;
}

private int getMessageLength(ByteArrayOutputStream contentLengthBaos) {
    byte[] firstFourBytesArr = contentLengthBaos.toByteArray();
    int contLen = new BigInteger(firstFourBytesArr).intValue();
    contentLengthBaos = new ByteArrayOutputStream();
    Log.d(TAG, "Content length: " + contLen);
    return contLen;
}

The server is started using the following lines of code:

Thread serverThread = new Thread(new Runnable() {
        @Override
        public void run() {
            startServer();
        }
    });
    serverThread.start();

I am getting the following error stack trace:

W/System.err: java.net.SocketException: Software caused connection abort
                  at java.net.SocketInputStream.socketRead0(Native Method)
                  at java.net.SocketInputStream.socketRead(SocketInputStream.java:114)
W/System.err:     at java.net.SocketInputStream.read(SocketInputStream.java:170)
W/System.err:     at java.net.SocketInputStream.read(SocketInputStream.java:139)
W/System.err:     at java.io.BufferedInputStream.fill(BufferedInputStream.java:248)
W/System.err:     at java.io.BufferedInputStream.read(BufferedInputStream.java:267)
                  at com.example.umathur.myapplication.MainActivity.startServer(MainActivity.java:192)
                  at com.example.umathur.myapplication.MainActivity.access$000(MainActivity.java:61)
                  at com.example.umathur.myapplication.MainActivity$1.run(MainActivity.java:139)
                  at java.lang.Thread.run(Thread.java:764)

I am getting an error called: java.net.SocketException: Software caused connection abort

I'm not sure where I'm going wrong in the usage of the inputstream/outputstream. Im getting the error at the following line(Line number 192 as mentioned in the stacktrace) :

while ((c = inputStream.read()) != -1)

In some similar questions on StackOverflow, I saw people stating that it might be a corporate firewall configuration issue ? Is that correct ? If so, how do I get it fixed ?

Could this be an issue with the Client code (To which I don't have access) not being written correctly ?

like image 736
Umang Mathur Avatar asked Jul 27 '18 19:07

Umang Mathur


People also ask

How do I fix Software caused connection abort socket write error?

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.

What does Software caused connection abort mean?

10.14 'Network error: Software caused connection abort' If the network between your client and server goes down and your client then tries to send some data, Windows will make several attempts to send the data and will then give up and kill the connection.


1 Answers

I can't reproduce your issue locally, and something tells me that your trigger conditions are pretty specific, but here are a few things to try to help you diagnose and fix your problem.

  1. Your code: If it's your code, then existing web server code should work. Try the code in the code from this nice minimal Medium article on how to create your own Java web server.
  2. The Firewall: If it's the firewall, contact your network admin person/team etc. If you don't know who it is, just talk to as high profile a person in your company that you feel comfortable asking and they should be able to direct you to the right person.
  3. Socket SO_KEEPALIVE Option: I found an interesting SuperUser question on the subject, and read that this issue may be caused by the fact that you don't have the SO_KEEPALIVE flag set on your socket. The answer talks about PuTTY, but I thought it it might be worthwhile to try on your Java socket. It's certainly a low hanging fruit to try. As such, try adding via calling connectionSocket.setKeepAlive(true); just after the Socket connectionSocket = serverSocket.accept(); line.
like image 89
entpnerd Avatar answered Sep 19 '22 03:09

entpnerd